CSS in React

How to style a React application with CSS

With React, you can add styles to components in many ways.

Use classes and CSS

The first and easiest way is to use classes and use normal CSS files to target these classes:

const Button = () => {
  return <button className="button">A button</button>
.button {
  background-color: yellow;

You can use the import statement to import the style sheet as follows:

import './style.css'

withWebpackWill be responsible for adding CSS properties to the bundle.

Use style attributes

The second method is to usestyleThe attributes attached to the JSX element. With this method, you don't need a separate CSS file.

const Button = () => {
  return <button style={{ backgroundColor: 'yellow' }}>A button</button>

The definition of CSS is now slightly different. First, note the double curly braces: this is becausestyleAccept an object. We pass in a JavaScript object, which is defined in curly braces. We can also do this:

const buttonStyle = { backgroundColor: 'yellow' }
const Button = () => {
  return <button style={buttonStyle}>A button</button>

when using itcreate-react-app, Because these styles are used, these styles are automatically prefixed by defaultAuto prefix.

In addition, the style is now camel case instead of using dashes. Whenever a CSS property has a dash, delete it, and then capitalize the next word.

The advantage of styles is that they are local to the component and will not leak to other components in other parts of the application, which cannot be provided using classes and external CSS files.

Use CSS modules

CSS moduleIt seems to be a perfect choice in the middle: you use classes, but CSS is limited to the scope of components, which means that any styles you add cannot be applied to other components without your permission. However, your style is defined in a separate CSS file, which is easier to maintain than CSS in JavaScript (and you can use old CSS property names).

First create a CSS file ending in.module.css, E.gButton.module.css. The best option is to give it the same name as the component to be styled

Add CSS here, and then import it into the component file to be styled:

import style from './Button.module.css'

Now you can use it in JSX:

const Button = () => {
  return <button className={style.content}>A button</button>

That's it! In the generated markup, React will generate a specific unique class for each rendered component and assign CSS to that class so that CSS will not affect other markup.

CSS Modules in React

Download mine for freeResponse Handbook

More response tutorials: