CSS Styling In React
Styling in React can be done in several ways, depending on your preferences and the complexity of your project. Here are the most common methods for applying CSS in React:
Inline Styles:
React allows us to apply styles directly to elements using the style attribute. The styles are written as a JavaScript object, with camelCase property names instead of kebab-case.
function App() {
const divStyle = {
color: 'blue',
backgroundColor: 'lightgray',
padding: '10px',
};
return <div style={divStyle}>Hello, React!</div>;
}
or we write style directly in style attribute as below
function App() {function App() {Note: We have to follow camel Case during writing in-line css style.
CSS Stylesheets:
We can create a separate CSS file and import it into your React component. This is the most traditional way of styling.
Example:
//App.jsx
import './App.css';
function App() {
return <divclassName="container">Hello, React!</div>;
}
App.css
.container {
color: blue;
background-color: lightgray;
padding: 10px;
}
CSS Modules:
CSS Modules allow you to scope styles locally to a component, avoiding conflicts with other styles in the application. You create a CSS file with the .module.css extension and import it into your component.
Example:
App.jsx
import styles from './App.module.css';
function App() {
return <div className={styles.container}>Hello, React!</div>;
}
App.module.css:
.container {
color: blue;
background-color: lightgray;
padding: 10px;
}
Styled Components (CSS-in-JS):
Styled Components is a popular library for writing CSS directly in your JavaScript files. It uses tagged template literals to define styles.
Example:
import styled from 'styled-components';
const Container = styled.div`
color: blue;
background-color: lightgray;
padding: 10px;
`;
function App() {
return <Container>Hello, React!</Container>;
}
Sass/SCSS:
React supports Sass/SCSS for more advanced styling features like variables, nesting, and mixins. You need to install sass to use it.
Example:
// App.scss
$primary-color: blue;
.container {
color: $primary-color;
background-color: lightgray;
padding: 10px;
}
App.jsx
import './App.scss';
function App() {
return <div className="container">Hello, React!</div>;
}
Global Styles with Libraries:
Libraries like styled-components or emotion also allow you to define global styles for your application.
Example with styled-components:
import { createGlobalStyle } from 'styled-components';
const GlobalStyle=createGlobalStyle`
body {
margin: 0;
font-family: Arial, sans-serif;
}
`;
function App() {
return (
<>
<GlobalStyle/>
<div>Hello, React!</div>
</>
);
}
Note:
In React, we use
classNameinstead ofclassbecauseclassis a reserved keyword in JavaScript. React is built on JavaScript, and usingclassas an attribute in JSX (JavaScript XML) would cause a conflict with theclasskeyword used to define classes in JavaScript.
