Can someone explain how to implement style encapsulation in a React app?

Viewed 2100

Looking at a webpage created with React, I see class names like class="pmjY9Fa_. I know about encapsulation, but am wondering when does the turning of human readable class names into a unique string happen? Looking at my own app (created with the basic create-react-app) the class names are still normal. Do I have to npm install something like css-modules? And if I do, what happens then? Like, I have to eject my CRA to add css-modules to my webpack configuration so when the app builds (either for development or production) the style names are hashed? Also, isn't it a bad development experience if the style names are all hashed?

My question his, how can I set up style encapsulation with hashed classes and still have a decent development experience with human readable class names?

edit: Also I'm trying to figure out how this is done without using Styled Components because the project I'm going to work on already uses scss co-located with the JSX files.

1 Answers

CSS Modules

create-react-app v2+

comes with out-of-box support for CSS Modules.

You DO NOT need to

  • eject,
  • Perform any additional webpack configs manually, or
  • Perform any npm install

Using CSS Modules with create-react-app (v2+) is very easy

  1. Name the css files associated with the component name like [name].module.css
  2. Add CSS classes to this file as you normally do, and import this css file into the React component like import styles from './[Name].module.css'
  3. Use the classes as you normally would like <header className={styles.header}>…</header>

When your application runs, the class names in the rendered DOM will be automatically mangled to prevent global conflicts. The runtime name will be something like [name]_header__1RvjY instead of just header, for example.

Here is a link explaining this in more detail. Here is the link to create-react-app CSS modules docs.

The second option is styled component Here is the official docs to get started. It is equally easy and it is just a matter of preference which one you choose.

So, in summary, whichever option you choose, you do not need to worry about global conflicts and have great developer experience.

Related