If you already use a methodology like BEM or SUIT, this is just a natural extension of that.
If you already use a methodology like BEM or SUIT, this is just a natural extension of that.
I know one of the larger motivations for managing styles directly in the react components was to solve a desire to have namespaces in CSS. Maybe there are other benefits that I am unaware of which would support handling styling directly in the react component.
But if you only partially implement your app / site in React, you have further complicated an already dense set of develop/styling abstractions. You will now have to think of your styling in terms of pre-instantiated app & post-instantiated app.
If you fully implement your app in React, you will most likely want to do away with traditional css all together with the exception of some base css libraries. CSS without cascades seems like a strange place to be.
class Header extends React.Component {
render() {
return (
<div className="Header">
<Logo />
<Avatar />
</div>
);
}
}
You want the Avatar to be floated to the right, so you do:.Header .Avatar { float: right; }
Unfortunately, this breaks encapsulation. It's basically monkey-patching and makes your components less portable. It causes a lot of problems in larger apps that aren't apparent until down the line.
So you could use BEM:
<div className="Header">
<Logo />
<Avatar className="Header__Avatar" />
</div>
This prevents many of the problems with global selectors, specificity, and encapsulation, but it gets repetitive and is a little ugly once things get more complicated. It's still pretty bug-prone. Another way to do it is: const styles = {
base: {
// ...
},
avatar: {
float: 'right'
}
};
<div style={styles.base}>
<Logo />
<Avatar style={styles.avatar} />
</div>
Which is how Radium and React Style do it. In this case, it might be <Avatar is="avatar" /> but it's the same idea. Specificity, modularity, namespacing, indeterminism, etc., are almost all fixed. Plus you now have the ability to dynamically compute values, import constants and functions, get values statically from CSS, and apply modifiers like `Header--loggedOut` by doing {this.props.isLoggedOut && styles.loggedOut}.Just like my JS requires different JS files, my CSS imports various files too. The preprocessor turns that into 1 css file (or n, if you want).
Then having a proper separation of code and style with class names to bind the two becomes your only sane option at scale.
import theme from 'styles/theme';