3 ms·
JSS (react-jss) has a couple plugins to handle this very well, and allows for nesting similar to scss/less. const styles = theme => ({ main: {
by tracker1 8y ago
JSS (react-jss) has a couple plugins to handle this very well, and allows for nesting similar to scss/less.
const styles = theme => ({
main: {
padding: theme.spacing.unit * 2,
fontFamily: theme.fonts.primary,
...
'&:hover': ...
'@media (max-width: 600px)': ...
},
inactive: {},
});
You get the benefit of the nested structure per class... but the added options of easily establishing the classNames, which are computed to be unique, so no conflicts in practice.
const FooComponent = ({ classes, inactive }) => (
<div
className={classnames(
classes.main,
{
[classes.inactive]: inactive
}
)}
>
...
</div>
)
In this way, you can bring in shared values from your theme. I can now inject different values into the theme from a central point in the application, via release, runtime, from an api/backend. I still have the option for psuedo selectors and media queries. There are more advantages with FAR less bugs than using CSS, even with SCSS/Less or other tooling.
Stylesheets are then generated with dynamic selectors, and the selectors are applied to the component, and the stylesheet is injected dynamically.
- danShumway 8y agoThis strikes me as a much more sane approach, which makes me really surprised that somehow I haven't heard about it until now. To me, the biggest problem in CSS that makes me not completely dismissive of JS-in-CSS is scoping (although BEM does kind of tend to solve that problem pretty well for me already). Dynamically generating the class names seems at first glance at least to be a good solution to that problem. Doing it as part of a compile step would be better than doing it clientside or serverside, but obviously that's not really feasible for most dynamic applications. Possibly there could be a Babel step that swaps out references in source code or something. But yeah, I'm interested into looking into this more. Thanks for letting me know!
- tracker1 8y agoThere are different CSS-in-JS libraries, I'm using react-jss[1] myself, which is the example... I'm also using it configured via material-ui[2] component library which has a couple addons for nested structures, psuedo-selectors, media queries etc. I believe there are options for many of them to run a pass through your components and generate CSS at build time, but I find that dynamically loading (react-loader) my components works out better overall, and don't notice the CSS generated at runtime in practice. I do inject a default style baseline that is enough for the app loader spinner, and the global error handler's output screen. [1] https://github.com/cssinjs/react-jss https://github.com/cssinjs/react-jss [2] https://material-ui.com/ https://material-ui.com/