DEV Community

loading...

Different Ways of Styling With React

shadowtime2000 profile image shadowtime2000 Originally published at h.shadowtime2000.com on ・2 min read

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

Discussion (4)

pic
Editor guide
Collapse
kamalhossain profile image
Kamal Hossain

can you suggest me any good example of CSS module?

Collapse
shadowtime2000 profile image
shadowtime2000 Author

I am a little confused by what you mean by this. Can you clarify?

Collapse
kamalhossain profile image
Kamal Hossain

I have wanted some good css module source code to go through over them.. if you know any.

Collapse
aalphaindia profile image