Different Ways of Styling With React

shadowtime2000

shadowtime2000

Posted on December 3, 2020

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>
        </>
    )
}
Enter fullscreen mode Exit fullscreen mode

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>
        </>
    )
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode
import styles from "./my-component.module.css";

function MyComponent() {
    return (
        <>
            <div className={styles.mycomponent}>This is my component</div>
        </>
    )
}
Enter fullscreen mode Exit fullscreen mode

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
💖 💪 🙅 🚩
shadowtime2000
shadowtime2000

Posted on December 3, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related