React CSS

There are many ways to work with CSS in React application.

The common approaches to work with CSS are

  • Regular CSS class
  • Style Attribute
  • CSS in JS

Regular CSS class

You can use className attribute to specify a CSS class.

Box.css

1
2
3
4
5
6
7
8
9
10
11
.Greenbox {
width: 300px;
height: 150px;
background-color: green;
}

.BlueBox {
width: 300px;
height: 150px;
background-color: blue;
}

In the component, you can import the CSS file import "./Box.css", then set className attribute. You can set className attribute as a String or assign it as a JSX expression.

Box.js

1
2
3
4
5
6
7
8
9
10
import "./Box.css";

function Box(props) {
let className = props.color === "green"? "GreenBox": "BlueBox"
return (
<div>
<div className={className}></div>
</div>
)
}

Style Attribute

The style attribute accepts a JavaScript object with camelCased properties rather than a CSS string. using the style attribtue as the primary means of styling elements is generally not recommended

1
2
3
4
5
6
7
8
9
10
let greenboxStyle = {
width: "300px",
height: "150px",
backgroundColor: "green"
}
return (
<div>
<div style={greenboxStyle}></div>
</div>
)

CSS in JS

“CSS-in-JS” refers to a pattern where CSS is composed using JavaScript instead of defined in external files.

Note that this functionality is not a part of React, but provided by third-party libraries. YOu can find a list of css-in-js library in here.

styled-components is a popular CSS in JS library, To install styled-components

1
npm install styled-components

Box.js

1
2
3
4
5
6
7
8
9
10
11
12
function Box(props) {
const GreenBox = styled.div`
width: 300px;
height: 150px;
background-color: green;
`
return (
<div>
<GreenBox />
</div>
)
}

CSS Modules Support

Create React App supports CSS Modules. CSS Modules is CSS files in which all class names and animation names are scoped locally by default.

see https://create-react-app.dev/docs/adding-a-css-modules-stylesheet/ for more details.

Box.module.css

1
2
3
4
5
6
7
8
9
10
11
.GreenBox {
width: 300px;
height: 150px;
background-color: green;
}

.BlueBox {
width: 300px;
height: 150px;
background-color: blue;
}

Box.js

1
2
3
4
5
6
7
8
9
10
import React from 'react'
import styles from './Box.module.css'

function Box(props) {
return (
<>
<div className={styles.GreenBox} />
</>
)
}

References