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 | .Greenbox { |
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 | import "./Box.css"; |
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 | let greenboxStyle = { |
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 | function Box(props) { |
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 | .GreenBox { |
Box.js
1 | import React from 'react' |