Different Ways of Styling With React

Different Ways of Styling With React

There a couple different ways you can style your React components.

We will go over:

  1. style attribute
  2. Just importing .css files
  3. CSS modules
  4. 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 importing .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 classNames 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 classNames 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:

  1. style attribute
  2. Just importing .css files
  3. CSS modules
  4. CSS-in-JS