Styling in React
React supports many styling approaches. Here are the most popular ones with examples.
1. CSS Modules (Recommended for most projects)
/* Button.module.css */
.button {
padding: 0.5rem 1rem;
border-radius: 6px;
font-weight: 600;
cursor: pointer;
transition: background 0.2s;
}
.primary { background: #3b82f6; color: white; }
.secondary { background: #e2e8f0; color: #1e293b; }
.danger { background: #ef4444; color: white; }
import styles from "./Button.module.css";
function Button({ label, variant = "primary" }) {
return (
<button className={`${styles.button} ${styles[variant]}`}>
{label}
</button>
);
}
2. Tailwind CSS (Popular with Vite + React)
// No CSS files โ utility classes applied directly
function Card({ title, description, badge }) {
return (
<div className="rounded-xl border border-slate-200 bg-white p-6 shadow-sm hover:shadow-md transition-shadow">
{badge && (
<span className="inline-block rounded-full bg-blue-100 px-3 py-1 text-xs font-semibold text-blue-700 mb-3">
{badge}
</span>
)}
<h2 className="text-xl font-bold text-slate-900 mb-2">{title}</h2>
<p className="text-slate-600 leading-relaxed">{description}</p>
</div>
);
}
3. Inline Styles (Useful for dynamic values)
function ProgressBar({ value, max = 100, color = "#3b82f6" }) {
const pct = (value / max * 100).toFixed(1);
return (
<div style={{ background: "#e2e8f0", borderRadius: 8, overflow: "hidden" }}>
<div
style={{
width: `${pct}%`,
height: 12,
background: color,
transition: "width 0.4s ease",
}}
/>
</div>
);
}
4. Styled-Components (CSS-in-JS)
npm install styled-components
import styled from "styled-components";
const Button = styled.button`
padding: 0.5rem 1rem;
border-radius: 6px;
font-weight: 600;
background: ${props => props.variant === "danger" ? "#ef4444" : "#3b82f6"};
color: white;
cursor: pointer;
&:hover {
opacity: 0.9;
}
`;
// Usage
<Button>Primary</Button>
<Button variant="danger">Delete</Button>
Choosing a Styling Approach
| Approach | Pros | Cons |
|---|---|---|
| CSS Modules | Scoped, no runtime cost, familiar CSS | Separate files |
| Tailwind CSS | Fast to write, consistent design tokens | Long class strings |
| Inline styles | Dynamic values, no class name collisions | No media queries, pseudo-classes |
| Styled-components | Full CSS power, co-located with component | Runtime overhead, larger bundle |