Styling in React
React supports multiple styling approaches — CSS modules, inline styles, and utility frameworks.
CSS Modules
Import scoped class names:
/* Button.module.css */
.primary {
background: blue;
color: white;
}
import styles from "./Button.module.css";
function Button() {
return <button className={styles.primary}>Click</button>;
}
Class names are scoped to avoid collisions.
Inline Styles
Use a style object for dynamic values:
function Box({ color }) {
return (
<div style={{ background: color, padding: "1rem" }}>
Dynamic style
</div>
);
}
Inline styles don’t support pseudo-classes or media queries.
Tailwind CSS
Use utility classes directly in JSX:
function Card() {
return (
<div className="rounded-lg shadow-md p-4 bg-white">
<h2 className="text-xl font-bold">Title</h2>
<p className="text-gray-600">Content</p>
</div>
);
}
Fast to build, no custom CSS files needed.
Conditional Classes
<button className={isActive ? "btn active" : "btn"}>
Toggle
</button>
Or with classnames library:
import cx from "classnames";
<button className={cx("btn", { active: isActive, large: size === "lg" })}>
Click
</button>
Best Practices
- Use CSS modules for scoped component styles
- Use Tailwind for rapid prototyping
- Keep inline styles for truly dynamic values only
- Extract repeated patterns into reusable classes
Common Mistakes
- Mixing inline styles with CSS specificity causes conflicts
- Using string concatenation for class names instead of
cx - Not purging unused CSS leads to large bundles