Comparing to writing your styles in a CSS file, React's style attribute has the following advantages:
However, the React's style attribute comes with a few drawbacks - you can't
Using CSS in JS, you can get all the advantages of a style tag, without those drawbacks. As of today, there are a few popular well-supported CSS in js-libraries, including Emotion, Styled-Components, and Radium. Those libraries are to CSS kind of what React is to HTML. They allow you to write your CSS and control your CSS in your JS code.
let's compare how our code will look for styling a simple element. We'll style a "hello world" div so it shows big on desktop and smaller on mobile.
Using the style attribute
return (
<div style={{fontSize:24}} className="hello-world">
Hello world
</div>
)
Since media query is not possible in a style tag, we'll have to add a className to the element and add a css rule.
@media screen and (max-width: 700px){
.hello-world {
font-size: 16px;
}
}
Using Emotion's 10 CSS tag
return (
<div
css={{
fontSize: 24,
[CSS_CONSTS.MOBILE_MAX_MEDIA_QUERY]:{
fontSize: 16
}
}
>
Hello world
</div>
)
Emotion also supports template strings as well as styled-components. So if you prefer you can write:
return (
<Box>
Hello world
</Box>
)
const Box = styled.div`
font-size: 24px;
${CSS_CONSTS.MOBILE_MAX_MEDIA_QUERY}{
font-size: 16px;
}
`
Behind the hoods "CSS in JS" uses CSS classes. Emotion specifically built with performance in mind and uses caching. Compared to React style attributes CSS in JS will provide better performance.
###Best Practices
Here are a few best practices I recommend:
Should I be aiming to do all styling this way, and have no styles at all specified in my CSS file?
should I avoid inline styles completely?
// option 1 - Write common styles in CONSTANT variables
// styles.js
export const COMMON_STYLES = {
BUTTON: css`
background-color: blue;
color: white;
:hover {
background-color: dark-blue;
}
`
}
// SomeButton.js
const SomeButton = (props) => {
...
return (
<button
css={COMMON_STYLES.BUTTON}
...
>
Click Me
</button>
)
}
// Option 2 - Write your common styles in a dedicated component
const Button = styled.button`
background-color: blue;
color: white;
:hover {
background-color: dark-blue;
}
`
const SomeButton = (props) => {
...
return (
<Button ...>
Click me
</Button>
)
}
React coding pattern is of encapsulated components - HTML and JS that controls a component is written in one file. That is where your css/style code to style that component belongs.
When necessary, add a styling prop to your component. This way you can reuse code and style written in a child component, and customize it to your specific needs by the parent component.
const Button = styled.button([COMMON_STYLES.BUTTON, props=>props.stl])
const SmallButton = (props)=>(
<Button
...
stl={css`font-size: 12px`}
>
Click me if you can see me
</Button>
)
const BigButton = (props) => (
<Button
...
stl={css`font-size: 30px;`}
>
Click me
</Button>
)