Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make React CSS import component-scoped?

Tags:

css

reactjs

I have several components which have the following CSS/component structure

About/style.css

.AboutContainer {
    # Some style
}

p > code {
    # Some style
}

And I import the CSS in the componet as follows

About/index.js

import './style.css';

export default class About extends Component {
    render() {
         # Return some component
    }
}

However, the CSS is imported in the <header> section and stays global-scope.

I was expecting CSS to be:

  1. Component-scoped in a way that the style is only applied to things that are only rendered within this component.
  2. Style for this component would disappear if the component is unmounted.

However, when inspecting from the browser, the styles are specified at the <header> section and gets applied to all the components

<header>
   // Stuff
   <style type="text/css">style for component About</style>
   <style type="text/css">style for component B</style>
   <style type="text/css">style for component C</style>
   // Stuff
</header>

How do I import CSS to be component-scoped? It seems like I'm understanding CSS import in React ES6 incorrectly.

I was following this tutorial


Edit

Answer by Brett is correct. However, my problem turns out to be somewhere else. I created my app using create-react-app which basically simplifies setups required to do React. It include WebPack, Babel and other things to get started. The default WebPack config that it uses did not set module option for the css-loader so it defaulted to false, and as a result the local-scoping was not enabled.

Just for additional info, it seems like create-react-app does not have straightforward way to customize WebPack config, but there seem to be numerous how-to workarounds on the web.

like image 715
Harry Cho Avatar asked Nov 03 '17 07:11

Harry Cho


People also ask

Is CSS scoped in React?

By default, CSS in React is scoped globally. This means that using the same className for 2 elements will cause a clash. One way to avoid clashes without any additional configuration is to make sure you're using unique class names for every component.

What is import {} In React?

Introduction. Importing and exporting in React JS will help us write modular code, i.e., splitting code into multiple files. Importing allows using contents from another file, whereas exporting makes the file contents eligible for importing.

How do I import a module into React CSS?

To import a CSS Module into the corresponding component, import the css modules stylesheet as styles or [name]Styles : In JSX, use the defined CSS class as a className prop like so: From here, you can add as many other CSS modules you'd like, just remember to import each as a different name.

What is scoped CSS?

The :scope CSS pseudo-class represents elements that are a reference point for selectors to match against. /* Selects a scoped element */ :scope { background-color: lime; } Currently, when used in a stylesheet, :scope is the same as :root , since there is not at this time a way to explicitly establish a scoped element.


4 Answers

It sounds like CSS Modules, or many of the other CSS-in-JS packages, does what you want. Others include Emotion (my current favorite), Styled Components, or many of the packages here.

A CSS Module is a CSS file in which all class names and animation names are scoped locally by default. All URLs (url(...)) and @imports are in module request format (./xxx and ../xxx means relative, xxx and xxx/yyy means in modules folder, i. e. in node_modules).

Here's a quick example:

Let's say we have a React component like:

import React from 'react';
import styles from './styles/button.css';

class Button extends React.Component {
  render() {
    return (
      <button className={styles.button}>
        Click Me
      </button>
    );
  }
}
export default Button;

and some CSS in ./styles/button.css of:

.button {
  border-radius: 3px;
  background-color: green;
  color: white;
}

After CSS Modules performs it's magic the generated CSS will be something like:

.button_3GjDE {
  border-radius: 3px;
  background-color: green;
  color: white;
}

where the _3DjDE is a randomly generated hash - giving the CSS class a unique name.

An Alternative

A simpler alternative would be to avoid using generic selectors (like p, code, etc) and adopt a class-based naming convention for components and elements. Even a convention like BEM would help in preventing the conflicts you're encountering.

Applying this to your example, you might go with:

.aboutContainer {
  # Some style
}

.aboutContainer__code {
  # Some style
}

Essentially all elements you need to style would receive a unique classname.

like image 185
Brett DeWoody Avatar answered Oct 18 '22 22:10

Brett DeWoody


Maybe react-scoped-css will help. Btw, I'm the author of this lib, if you find anything broken or simply want to improve it, you can always raise an issue or send a pr.

like image 23
Liang Avatar answered Oct 18 '22 22:10

Liang


Because you mentioned you used create-react-app, the solution here is quite easy change just style.css to style.module.css, it will look like this:

import styles from "./style.module.css"
<button className={styles.button}>blabla</button>

More info on this article: https://blog.bitsrc.io/how-to-use-sass-and-css-modules-with-create-react-app-83fa8b805e5e

like image 12
Roni Litman Avatar answered Oct 18 '22 23:10

Roni Litman


You can use SASS (.scss) to imitate scoped CSS.

Say you need to use bootstrap in only one component (to avoid conflicts). Wrap the component in <div className='use-bootstrap'> and then created a .scss file like so:

.use-bootstrap {   
  // Paste bootstrap.min.css here
}
like image 11
vinays84 Avatar answered Oct 18 '22 22:10

vinays84