CSS in JSX
I have been working on some new React projects and the way that the CSS works in JavaScript seemed odd and simple to me at the same time. I like the idea of working with JSON objects but thought it was odd that most of the demos I have seen never did much outside of the simple inline CSS.
This is what most of them show.
<div style={{background:'red'}}>Hello World!</div>
Basically, you are putting a Javascript object of {background = 'red'}
as an inline style.
The next step would be to pull this out to a const and then put that in the style. This start to look more like normal CSS.
render() {
const style = {
background: 'red'
}
return (
<div>
<div style={style}>Hello World! Object</div>
</div>
);
}
And this works well at a CSS class level but when you want to do more you start getting stuck. This is where the concept of cascading comes in.
This is what it looks like in normal CSS
<style>
.Item{
background:"Red";
}
.Item .Large{
font-size:30px;
}
</style>
<div class="Item">Item 1</div>
<div class="Item Large">Item 2</div>
Then in JSX
render() {
const style = {}
style.Item = {
background: 'red'
};
style.Item.Large = {
... style.Item,
fontSize: 30
}
return (
<div>
<div style={style.Item}>Hello World! Cascading </div>
<div style={style.Item.Large}>Hello World! Cascading Large</div>
</div>
);
}
In the JSX I started using the spread operator ...
to copy down the items in the related object or cascade them.
I had this aha๐คฆโโ๏ธ moment a few days ago and hope this helps someone down the path of CSS in JavaScript in React.
Top comments (1)
Cool concept. You might just wanna look out for mutating the
styles
object. In the end when you're passingstyles.Item
it'll look like this:Which isn't a valid styles object. If you introduce types to your code, you'll get an error.