The bese way to use CSS in React, should be using CSS files.

Inline Styling

  • Using two sets of curly braces {{}}.
  • CSS properties with hyphen separators, like background-color, must be written with camel case syntax:
    const Header = () => {
    return (
      <>
        <h1 style={{backgroundColor: "lightblue"}}>Hello Style!</h1>
      </>
    );
    }
    
  • Use JavaScript Object:
    const Header = () => {
    const myStyle = {
      backgroundColor: "DodgerBlue",
      fontFamily: "Sans-Serif"
    };
    return (
      <>
        <h1 style={myStyle}>Hello Style!</h1>
      </>
    );
    }
    

CSS file

The bese way in Using CSS files. You can write your CSS styling in a separate file, just save the file with the .css file extension, and import it in your application.

Define your styles in a separate *.css file as usual and refer to them using className.

Create a file called “App.css” and insert some CSS code in it. Import the stylesheet in your application:

import "./Components/css/App.css";
function App() {
  return (
    <div className="main">
    </div>
  );
}

It is common for CSS classes to depend on the component props or state:

render() {
  let className = 'menu';
  if (this.props.isActive) {
    className += ' menu-active';
  }
  return <span className={className}>Menu</span>
}

CSS Modules

CSS Modules is not an official spec or an implementation in the browser but rather a process in a build step (with the help of Webpack or Browserify) that changes class names and selectors to be scoped (i.e. kinda like namespaced).

CSS Modules works by compiling individual CSS files into both CSS and data.

  • The CSS output is normal, global CSS, which can be injected directly into the browser or concatenated together and written to a file for production use.
  • The data is used to map the human-readable names you’ve used in the files to the globally-safe output CSS.

Here is the Offical doc for css-modules.

For more information about Webpack configuration, follow these links to the official documentation:

Why We need CSS Modules

This approach is designed to fix the problem of the global scope in CSS. global scope in CSS cause a lot of problem in SPA. For example,

  • you need to create many names for class,
  • you may affect other html when you modify or delete one class, etc.

How CSS Moduels work

Here’s an example of how that might work:

import styles from "./styles.css";

element.innerHTML = 
  `<h1 class="${styles.title}">
     An example heading
   </h1>`;

During the build step, the compiler would search through that styles.css file that we’ve imported, then look through the JavaScript we’ve written and make the .title class accessible via styles.title. Our build step would then process both these things into new, separate HTML and CSS files, with a new string of characters replacing both the HTML class and the CSS selector class.

Our generated HTML might look like this:

<h1 class="_styles__title_309571057">
  An example heading
</h1>

Our generated CSS might look like this:

._styles__title_309571057 {
  background-color: red;
}

Importing and applying styles

A CSS Module stylesheet is similar to a regular stylesheet, only with a different extension (e.g. styles.module.css). CSS Modules allows us to use the same class name in multiple files without clashes.

The CSS inside a module is available only for the component that imported it.

  1. Create the CSS module with the .module.css extension, example: my-style.module.css. my-style.module.css:
    .bigblue {
      color: DodgerBlue;
      padding: 40px;
      font-family: Sans-Serif;
      text-align: center;
    }
    
  2. Import the stylesheet in your component:
    import styles from './my-style.module.css'; 
    const Car = () => {
      return <h1 className={styles.bigblue}>Hello Car!</h1>;
    }
    export default Car;
    

    Because it is referenced as a js object, so No clashes from other .bigblue class names

Any valid .css file can be a CSS module. You don’t have to add .module in the file name.

Creating and composing CSS modules

The composes property is used in CSS module files to combine local style definitions. The following example creates a CSS module that applies the .heading style definition wherever .titleHighlighted is used.

/** ./styles.css */
.heading {
  color: yellow;
  background-color: blue;
  margin: 0 0 1rem;
}

.titleHighlighted {
  composes: heading;
  padding: 1rem 2rem;
  text-align: center;
}

You can Compose from another file. To reuse a definition from another file, use the from keyword.

/* default_heading.css */
.baseHeading {
  color: yellow;
  background-color: blue;
  margin: 0 0 1rem;
}

/* styles.css */
.heading {
  composes: baseHeading from "./default_heading.css";
  font-weight: bold;
}

CSS-in-JS

“CSS-in-JS” refers to a pattern where CSS is composed using JavaScript instead of defined in external files. This functionality is not a part of React, but provided by third-party libraries.

Popular libraries like: styled-components, Emotion. More information here.

Using Sass in React

If you use the create-react-app in your project, you can easily install and use Sass in your React projects. Install SASS: npm i sass After Sass installation, you can include Sass files in the React project. SASS file:

$myColor: red;
h1 {
  color: $myColor;
}

React:

import './my-sass.scss';
const Header = () => {
  return (
    <>
      <h1>Hello Style!</h1>
      <p>Add a little style!.</p>
    </>
  );
}

References