19. Styling in React: CSS Modules, Styled-Components, or Tailwind CSS
Why Styling Matters in React
React doesn’t include built-in styling tools, so developers choose from several methods to style components. The method you choose impacts reusability, scalability, and developer experience.
Option 1: CSS Modules
CSS Modules let you write regular CSS in separate files, but scope it locally to each component to avoid class name collisions.
/* Button.module.css */
.button {
background: royalblue;
color: white;
padding: 10px 16px;
border-radius: 6px;
border: none;
cursor: pointer;
}// Button.jsx
import styles from './Button.module.css'
function Button() {
return <button className={styles.button}>Click Me</button>
}
export default ButtonOption 2: Styled Components
Styled-components is a CSS-in-JS library that lets you write actual CSS in your JavaScript files and attach styles directly to components.
npm install styled-componentsimport styled from 'styled-components'
const Button = styled.button`
background: royalblue;
color: white;
padding: 10px 16px;
border-radius: 6px;
border: none;
cursor: pointer;
`
function App() {
return <Button>Click Me</Button>
}
export default AppStyled-components also supports props for conditional styling.
const Button = styled.button`
background: ${props => props.primary ? 'royalblue' : '#ccc'};
color: white;
padding: 10px 16px;
border-radius: 6px;
`
<Button primary>Primary Button</Button>Option 3: Tailwind CSS
Tailwind CSS is a utility-first CSS framework that lets you build modern UIs quickly by combining utility classes directly in your JSX.
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p// tailwind.config.js
module.exports = {
content: ['./index.html', './src/**/*.{js,jsx,ts,tsx}'],
theme: { extend: {} },
plugins: [],
}/* index.css */
@tailwind base;
@tailwind components;
@tailwind utilities;// Tailwind button example
function Button() {
return (
<button className="bg-blue-600 hover:bg-blue-700 text-white py-2 px-4 rounded-md">
Click Me
</button>
)
}
export default ButtonComparison Table
| Feature | CSS Modules | Styled Components | Tailwind CSS |
|---|---|---|---|
| Learning Curve | Easy | Moderate | Easy |
| Performance | High | Medium | High |
| CSS Reusability | Good | Excellent | Utility-Based |
| Setup Required | Minimal | Yes | Yes |
| Scoped Styles | ✅ | ✅ | ✅ |
Mini Project Step
Style your mini project components using any of these three methods. Choose one approach and apply consistent, reusable styling to your project layout.