Different Ways of Styling With React
There a couple different ways you can style your React components.
We will go over:
style
attribute- Just
import
ing.css
files - CSS modules
- CSS-in-JS
style
Attribute
React supplies a style
attribute you can use on plain elements. An example:
function MyComponent() {
return (
<>
<div style={{ color: "red" }}>Red div!</div>
</>
)
}
This approach is not recommended because it is not as performant compared to the other options. You can read more about it on the React docs.
Just import
ing .css
files
NOTE This only works when you are using a module bundler which supports CSS.
Some module bundlers allow you to just import
.css
files and it will apply appropriate transformations so it is available in your app.
import "./my-component.css";
function MyComponent() {
return (
<>
<div className="my-component">This is my component</div>
</>
)
}
CSS modules
NOTE CSS modules are built on PostCSS so you must make sure you bundler is configured for that.
CSS modules let you "import" your className
s into your app and it will append a unique hash to each of them at build time to make sure they are unique.
.mycomponent {
color: red;
}
import styles from "./my-component.module.css";
function MyComponent() {
return (
<>
<div className={styles.mycomponent}>This is my component</div>
</>
)
}
CSS-in-JS
CSS-in-JS is a pattern which allows you to write your CSS in JS and it will create unique hashes for those className
s which get appended to the styles.
You can read more about CSS-in-JS in an article I wrote.
Conclusion
We have gone over 4 different ways to style React components:
style
attribute- Just
import
ing.css
files - CSS modules
- CSS-in-JS