React pseudo selector inline styling - css

What do you think are good ways to handle styling pseudo selectors with React inline styling? What are the gains and drawbacks?
Say you have a styles.js file for each React component. You style your component with that styles file. But then you want to do a hover effect on a button (or whatever).
One way is to have a global CSS file and handle styling pseudo selectors that way. Here, the class 'label-hover' comes from a global CSS file and styles.label comes from the components style file.
<ControlLabel style={styles.label} className='label-hover'>
Email
</ControlLabel>
Another way is to style the components based on certain conditions (that might be triggered by state or whatever). Here, if hovered state is true, use styles.button and styles.buttonHover otherwise just use styles.button.
<section
style={(hovered !== true) ?
{styles.button} :
{...styles.button, ...styles.buttonHover }>
</section>
Both approaches feels kind of hacky. If anyone has a better approach, I'd love to know. Thanks!

My advice to anyone wanting to do inline styling with React is to use Radium as well.
It supports :hover, :focus and :active pseudo-selectors with minimal effort on your part
import Radium from 'radium'
const style = {
color: '#000000',
':hover': {
color: '#ffffff'
}
};
const MyComponent = () => {
return (
<section style={style}>
</section>
);
};
const MyStyledComponent = Radium(MyComponent);
Update 04/03/2018
This has been getting a few upvotes lately so I feel like I should update it as I've stopped using Radium. I'm not saying Radium isn't still good and great for doing psuedo selectors, just that it's not the only option.
There has been a large number of css-in-js libraries since Radium came out which are worth considering. My current pick of the bunch is emotion, but I encourage you to try a few out and find the one that fits you best.
emotion - 👩‍🎤 The Next Generation of CSS-in-JS
fela - Universal, Dynamic & High-Performance Styling in JavaScript
styled-jss - Styled Components on top of JSS
react-jss - JSS integration for React
jss - JSS is a CSS authoring tool which uses JavaScript as a host language
rockey - Stressless CSS for components using JS. Write Component Based CSS with functional mixins.
styled-components - Universal, Dynamic & High-Performance Styling in JavaScript
aphrodite - It's inline styles, but they work! Also supports styling via CSS
csx - ϟ A CSS-in-JS solution for functional CSS in functional UI components
styled-jsx - Full CSS support for JSX without compromises
glam - crazy good css in your js
glamor - css in your javascript
glamorous - React component styling solved with an elegant API, small footprint, and great performance (via glamor)
styletron - ⚡️ Universal, high-performance JavaScript styles
radium - Set of tools to manage inline styles on React elements.
aesthetic - Aesthetic is a powerful React library for styling components, whether it be CSS-in-JS using objects, importing stylesheets, or simply referencing external class names.
j2c - CSS in JS library, tiny yet featureful
(Source)

Is there a reason you're not styling the pseudo selectors with your label-hover class like this? Or am I misunderstanding your question?
.label-hover {
color: orange;
opacity: 0.5;
}
.label-hover:hover {
opacity: 1;
}
You can't style pseudo selectors with inline styling (CSS Pseudo-classes with inline styles), and I think using javascript to see if the element is hovered is an unnecessarily complicated and hackish way of doing it.

Related

When to use props and CSS to style Material UI elements?

I'm new to Material UI. When should I use props (in the .jsx script itself) and CSS (separate CSS stylesheet) to style MUI elements? Do I still need to use the CSS stylesheets for MUI elements at all, e.g. use CSS or sx={{}} prop? Or should it be left for non-MUI elements only?
While I understand MUI provides us with the template to make style changes using props, I also understand that we should typically follow a separation of concerns, hence the question.
Thanks a lot!
So you can check this out in their docs below.
https://mui.com/material-ui/customization/how-to-customize/#2-reusable-component
I personally wouldn't use CSS with MUI. You can use either CSS or the sx prop to override styles, however it feels like sx is the preferred method. Using CSS requires targeting the specific classname and nesting your classes which I find is quite a lot of work for what is meant to be one-off customizations.
If you wanted to change specific MUI components, I still wouldn't use CSS as you can just create your own themes with the ThemeProvider.
The idea behind MUI is a CSS-in-JS solution so you're sort of doing away with the concept of the traditional "separation of concerns". If you prefer to set up your projects that way, things like Tailwind or SASS/SCSS are more suited to that.
So in summary, yeah I'd only use CSS with the non-MUI components, sx prop for quick style overrides, and the ThemeProvider for global style changes.

what is the benefit of using styled components over using css class for the components

We write css when we use styled components, and I dont understand the benefit of using it why we just dont use the css we write as a classname for the components. In styled components we have wrappers of the components and when we use plain css we have class names. what is the advantage of wrapping components with styled components
The reason styled components is pushed in React web development is to encapsulate styles to only those components. There is no risk of bleeding css into other components. Rather than learn a new css organisation structure new developers can onboard more quickly.
That being said, it is restrictive, slower to develop with, and adds some page weight by applying same styles you could have shared.
I have found the fastest way to work is create static html webpages with pure css, and organise it in a way you are going to import it into your framework. Then you can have boilerplate html designs that can be tested independently of the compiler, which is so much faster to test in Internet Explorer, Firefox, chrome, mobile devices and all the varying screen sizes.
If you want to use styled components, you can either use this npm plugin to convert your static css into variables to use with style components -
https://www.npmjs.com/package/#inspiraller/create-css-vars
or just don't. Nextjs does not support css imports unless its global, so webpack compiling option is a more universal solution.
Main benefits of styled-components are listed in the Motivations page on their website.
styled-components is the result of wondering how we could enhance CSS for styling React component systems. By focusing on a single use case we managed to optimize the experience for developers as well as the output for end users.
Apart from the improved experience for developers, styled-components provides:
Automatic critical CSS: styled-components keeps track of which components are rendered on a page and injects their styles and nothing else, fully automatically. Combined with code splitting, this means your users load the least amount of code necessary.
No class name bugs: styled-components generates unique class names for your styles. You never have to worry about duplication, overlap or misspellings.
Easier deletion of CSS: it can be hard to know whether a class name is used somewhere in your codebase. styled-components makes it obvious, as every bit of styling is tied to a specific component. If the component is unused (which tooling can detect) and gets deleted, all its styles get deleted with it.
Simple dynamic styling: adapting the styling of a component based on its props or a global theme is simple and intuitive without having to manually manage dozens of classes.
Painless maintenance: you never have to hunt across different files to find the styling affecting your component, so maintenance is a piece of cake no matter how big your codebase is.
Automatic vendor prefixing: write your CSS to the current standard and let styled-components handle the rest.
With styled components it's possible to "enhance" CSS classes with JavaScript code because are written in JS.
const Input = styled.input`
color: ${props => props.hasError ? 'red' : 'black'};
`;
Opposed to writing 2 separate CSS classes and control which to show with JS.
.text {
color: black;
}
.text--danger {
color: red;
}
<input className={`text ${hasError ? 'text--danger' : ''}`} />
On the long run it can produce more maintainable code, but it's a matter of personal opinion if it's better to use it or not.
With styled components you can add logic programming

When to use CSS and JSX styles in React

I am learning React and realized that you can use either real CSS by importing a CSS file, or you can use JS which has CSS-like code using camel cases.
Example for pure CSS: import './AppStyle.css' which contains background-color: black;
Example for JS version: const AppStyle = { backgroundColor: "black" }
Which one is better to use and why? Or maybe they’re both fine?
Writing CSS allows all the benefits of CSS (like selectors, media query).
In inline styles, you write Object-like styles vs. actual CSS.
Code readability is worst in inline style implementation, while managing styles using the CSS is easy to maintain.
The inline styles take more space in DOM because all the styles are defined internally along with the DOM element, while CSS is described separately, creating no issues for the compiler while compiling the file.
There is ups and down with both solutions, you can achieve the same result with both, so it comes down to you want styling solution you prefer
Based on my experience,JSX and CSS are different technologies to solve the styling problem.
Good points of css:
css selectors
styling into css files
Good points of js:
js into styling -> sometimes you want to calculate styles over js https://cssinjs.org/jss-plugin-rule-value-function/?v=v10.0.0-alpha.3#enables-functions-for-dynamic-styles
more approaches to solve one problem -> it has js
Recommendation: Try to use one, it reduce the complexity and documentation to read.

What does in JSX react <div css=?

I have a simple react component it has in the JSX the property css, I understand this prop it is for styling, but it is not clear if it is a "native" css react property, or if it comes from styled-components or some other library.
Do you have an idea from which library it is if not a react one?
<div css={{color: 'red', backgroundColor:'blue'}}>Hello world!</div>;
css prop comes from styled-components library itself. It is to be used when a small bit of styling does not warrant making a component for it.
However, it is not implemented centrally in the library and functions with the help of the Babel plugin. This is why you don't need to import the function to use it.
Docs
It comes from Glamor which provides many convenient ways to style your components. One way is to use its css prop as in your example. It works exactly the same as the default style prop except it supports the entire CSS language.
Here an example:
https://github.com/threepointone/glamor/blob/master/docs/howto.md

Share CSS styles across web components

I am using mozilla - X-tabs, web components in my application for tabbing it. Now, i need to use bootstrap - glyphicons in my app. But since webcomponents use shadow-DOM, bootstrap css styles are not applied inside web components?
Is there a way around it, to share a css file/style for all web components?
You possibly want to read CSS Scoping Model by W3C.
Each polyfill library (I’m sure, e.g., Mozilla’s does) provides handlers for /deep/, ::content etc selectors.
Hope it helps.
We faced a similar scenario with font-awesome. We had a bunch of classes that are common across web components. We loaded them directly from the host and made those classes available to components using /deep/ combinator (soon going to be replaced with >>> syntax)
The polyfill (Webcomponents.js - from Polymer) used by X-tags has support for /deep/ and ::shadow (single level). You can use these selectors to target shadow DOM from outside.
Polymer provides an element core-style for this, see here.
This blog post goes through how to set it up, you use the same tag to declare the common styles and to import them.
<core-style id="button">
button {
display: inline-block;
background: #bada55;
}
</core-style>
The presence of an id makes this element a producer of common styles.
Then to import the common styles inside the shadow dom of a component:
<core-style ref="button"></core-style>
The ref attribute makes this a style consumer.
So AFIK its not possible in a standard way yet with plain web components, but there's the core-style extension in Polymer, or the Polymer support for ::shadow and /deep/selectors.
Web components supports css stylesheet import:
<template id="template-for-your-component">
your web component
<link href='./.../share-rules.css' rel='stylesheet' />
</template>
You can have a global stylesheet shares between all your components without duplicate your rules.

Resources