Skip to main content
Albero Academy

Styling in React

The ways to style components — plain CSS, CSS Modules, utility classes, CSS-in-JS — and how to apply classes conditionally.

Chapter 15React13 min readBeginner friendly
  • #React
  • #Styling
  • #CSS

React doesn't dictate how you style — it just renders className. That freedom means several popular approaches, each with trade-offs. This chapter surveys them so you can pick sensibly, and covers the everyday task of toggling classes based on state.

The options

ApproachGist
Plain CSSImport a .css file; global class names
CSS ModulesLocally-scoped class names — no clashes
Utility (Tailwind)Compose classes in the markup
CSS-in-JSWrite styles in JS (styled-components, Emotion)
Inline styleThe style prop — an object; use sparingly
inline styles are objects
<div style={{ color: "#2563eb", padding: 16, borderRadius: 12 }}>…</div>
// camelCase keys, values are strings or numbers (px assumed). Good for
// dynamic one-offs; not for whole stylesheets.

CSS Modules

A CSS Module scopes class names to the component, so .card in one file never collides with another:

Card.module.css + Card.jsx
/* Card.module.css */
.card { border: 1px solid #e5e7eb; border-radius: 12px; }
// Card.jsx
import styles from "./Card.module.css";
<div className={styles.card}>…</div> // becomes a unique hashed name

Utility classes

Utility frameworks (Tailwind) let you compose styles directly in markup — fast to write, no naming, styles co-located with the component:

utility classes
<button className="px-6 py-3 rounded-lg bg-blue-600 text-white hover:bg-blue-700">
Enrol
</button>

Conditional classes

toggling classes by state
// Template literal
<div className={`card ${active ? "card--active" : ""}`}>…</div>
// A tiny helper (or the clsx/classnames library) keeps it tidy
const cx = (...c) => c.filter(Boolean).join(" ");
<div className={cx("card", active && "card--active", error && "card--error")}>

Practice

Style a Card component with a CSS Module (scoped class), then rebuild it with utility classes. Add an active prop that toggles a modifier class using a cx helper, and one dynamic inline style driven by a prop.

Key takeaways

  1. 01React just renders className — pick from plain CSS, CSS Modules, utility (Tailwind) or CSS-in-JS.
  2. 02CSS Modules scope class names locally to avoid clashes.
  3. 03Utility classes compose styles in markup — fast, co-located, no naming.
  4. 04Inline style is an object with camelCase keys — for dynamic one-offs, not whole sheets.
  5. 05Toggle classes with template literals or a cx/clsx helper based on state.