Styling in React has evolved significantly over the past decade. Because React components are modular and self-contained, keeping CSS styles encapsulated with their respective component prevents global scope leakage and makes codebases easy to refactor.
Supported out-of-the-box by Vite and Next.js without any configuration. Name your file with the .module.css suffix:
/* src/components/Button.module.css */
.primaryButton {
background-color: #5dbe59;
color: #ffffff;
padding: 10px 20px;
border: none;
border-radius: 6px;
font-weight: 700;
cursor: pointer;
transition: opacity 0.2s ease;
}
.primaryButton:hover {
opacity: 0.9;
}
Import it as an object inside your component JSX file:
// src/components/Button.jsx
import React from 'react';
import styles from './Button.module.css';
function Button({ children, onClick }) {
// styles.primaryButton compiles to a unique hash: Button_primaryButton__d78a9
return (
<button className={styles.primaryButton} onClick={onClick}>
{children}
</button>
);
}
export default Button;
Best suited for dynamic styles computed from state or props at runtime (e.g. progress bar widths, positioning):
function ProgressBar({ percentage }) {
const barStyle = {
width: `${percentage}%`,
backgroundColor: percentage === 100 ? '#5dbe59' : '#38bdf8',
height: '12px',
borderRadius: '6px',
transition: 'width 0.4s ease'
};
return (
<div style={{ background: '#e2e8f0', borderRadius: '6px' }}>
<div style={barStyle}></div>
</div>
);
}
Tailwind CSS is the dominant industry styling tool for modern React applications. You apply atomic utility classes directly into your JSX:
function FeatureCard({ title, description }) {
return (
<div className="p-6 max-w-sm mx-auto bg-white rounded-xl shadow-md flex items-center space-x-4 border border-slate-100">
<div className="text-xl font-medium text-black">{title}</div>
<p className="text-slate-500 text-sm">{description}</p>
</div>
);
}
Now let us step into React's most vital lifecycle hook in React useEffect & Side Effects.
Accelerate your React mastery by studying these tightly connected core tutorials:
Scoped styling per component file.
Z-index management and portal container styling.
Flexbox, CSS Grid, and responsive web design.