Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 132 ยท Components and Props

Styling React Components

Learn how to style React components with className, inline style objects, CSS variables, conditional classes, CSS Modules, Tailwind and CSS-in-JS, with accessible focus styles.

React does not ship its own styling system. A React component produces ordinary DOM elements, and those elements are styled by ordinary CSS: the same properties, selectors and cascade you already know from the CSS tutorial. What React adds is a way to choose styles from data. Because a component is a function of its props and state, the classes and style values it outputs can change whenever that data changes.

This lesson covers the options you will meet in real projects: className with stylesheets, inline style objects, CSS custom properties, conditional classes, and the families of tools built on top (CSS Modules, utility classes such as Tailwind, and CSS-in-JS). It ends with the part people forget: styles are also an accessibility concern, especially focus outlines.

className, not class

In JSX you write className instead of class. The reason is historical: class is a reserved word in JavaScript, and JSX attributes become properties of a plain object (props), which in turn map to DOM properties. The DOM property for the class attribute has always been className, so React uses that name.

className with a style element

Here the CSS lives in a <style> element inside the component so the example is self-contained. In a real project you would put the rules in a .css file and import it (see below). Either way, the component only says which class an element has; the stylesheet decides what that class looks like.

Remember that in JSX the attribute is htmlFor for <label> too, and that event and many other attributes are camelCase. See JSX basics for the full list.

Stylesheets in a real project

In a project created with Vite or a framework, you import a CSS file for its side effect:

JSX
// Button.jsx  (read-only: needs a bundler that understands CSS imports)
import './Button.css';

export function Button({ children }) {
  return <button className="button">{children}</button>;
}

The bundler collects all imported CSS into the page. Notice that CSS is global: .button applies to every element with that class anywhere on the page, no matter which component imported the file. For small apps that is fine. In big ones, two teams will eventually both define .card and silently break each other. The usual cures are a naming convention (BEM, such as .card__title--large), CSS Modules, utility classes, or CSS-in-JS. We look at each below.

Our live editor runs a single module without a bundler, so import './Button.css' is not available in the examples. We use a <style> element or inline styles instead. Blocks marked read-only show what a real project looks like.

Inline style objects

The style prop does not take a string like HTML's style="color: red". It takes a JavaScript object. Property names are written in camelCase (backgroundColor, not background-color), and values are usually strings.

Inline styles are objects

Three details to remember:

  • Numbers get px. padding: 16 becomes 16px, and so do borderRadius: 8 and fontSize: 20. Unitless properties such as lineHeight, opacity, flex and zIndex stay unitless. For any other unit write a string: width: '50%', margin: '0 auto'.
  • The double braces are not special syntax. The outer pair means "a JavaScript expression goes here"; the inner pair is an object literal. You can also build the object elsewhere (like cardStyle above) and pass it by name. Defining a constant outside the component also avoids creating a new object on every render.
  • Inline styles cannot express everything. There are no :hover, :focus or ::before selectors, no media queries, and no @keyframes. They also have very high specificity, which makes them hard to override. Use them for values that are truly dynamic (a width computed from data, a color chosen by the user), and reach for classes for everything else.

Conditional classes

Most styling in React comes down to one question: which classes should this element have right now? Build the string from props and state.

Choosing classes from state

When there are several optional classes, a ternary quickly gets ugly. Two common ways to keep it readable:

JSX
// 1. Join the truthy parts yourself
const className = ['tag', selected && 'tag-selected', disabled && 'tag-disabled']
  .filter(Boolean)
  .join(' ');

// 2. Use the tiny `clsx` package (read-only: npm install clsx)
import clsx from 'clsx';
const className = clsx('tag', { 'tag-selected': selected, 'tag-disabled': disabled });

Two pitfalls. Never produce the string "undefined" or "false" by writing `tag ${selected && 'tag-selected'}`: when selected is false the class list becomes tag false. And prefer a class that describes the state (is-selected, or a data attribute such as data-state="open") over one that describes the look (blue), so you can restyle without touching the component.

Also notice aria-pressed on the button: the color alone tells sighted users it is on, but screen reader users need the state in the markup.

CSS custom properties (variables)

CSS variables are a perfect bridge between React state and a stylesheet. The stylesheet defines how things look in terms of variables; React only sets a few variable values. You can set them through the style prop, since custom property names starting with -- are passed through as they are.

Theming with CSS variables

Changing a variable restyles everything that uses it, with no extra React work, and children inherit the variables from the element that sets them. Compared with generating a whole style object per theme, this keeps the CSS in CSS. Variables also respond to media queries and to prefers-color-scheme, which JavaScript-in-JavaScript approaches have to emulate.

Dark mode and a theme toggle

A theme toggle is one of the most requested features and a good exercise in combining the tools above: CSS variables for the colors, a bit of state for the choice, context so any component can read or change it, and the browser for two things React cannot know, the system preference and saved settings.

Three choices, not two

Do not model the theme as a boolean. People expect three options:

  • Light: always light.
  • Dark: always dark.
  • System: follow the operating system, and change live when the system switches (many phones do at sunset).

So the stored value is 'light' | 'dark' | 'system', and the resolved theme ('light' or 'dark') is derived from it. Deriving beats storing: do not keep a second state for the resolved value.

Colors live in CSS variables

Define the palette once per theme as custom properties on an element that wraps the app, and write every component against the variable names. Switching themes then means changing one attribute, and no component re-renders because of colors. Setting color-scheme also tells the browser to darken built-in controls (scrollbars, form fields):

CSS
:root {
  --bg: #ffffff;
  --text: #0f172a;
  --accent: #2563eb;
  color-scheme: light;
}
[data-theme="dark"] {
  --bg: #0f172a;
  --text: #e2e8f0;
  --accent: #60a5fa;
  color-scheme: dark;
}
body { background: var(--bg); color: var(--text); }

Reading the system preference

window.matchMedia('(prefers-color-scheme: dark)') returns a MediaQueryList whose matches is the current answer and which fires a change event when the system switches. That is an external value that changes over time, so the clean way to read it in React is useSyncExternalStore (see external stores); a useEffect with an event listener also works.

Persistence, and its sandbox limit

To remember the choice, save it in localStorage and read it on startup. Browsers can throw when storage is blocked (private modes, restricted iframes), so always wrap access in try/catch and fall back to 'system'. In this site's editor the preview is a sandbox without storage, so the read throws and the code falls back, which is exactly what the demo shows. In a real app, the saved choice survives reloads.

Light, dark and system theme with context, variables and safe storage

Pick system, then switch your operating system between light and dark (or use your browser's rendering emulation): the page follows without a reload, because useSyncExternalStore re-renders when the media query changes.

Avoiding the flash of the wrong theme

If the theme is applied by React after hydration, a dark-mode user sees a white flash first. In a server-rendered or Vite app, put a tiny blocking script in the <head> (before the body renders) that reads the saved choice and sets data-theme on <html> immediately; React then takes over with the same value. This is read-only code, because it lives in index.html:

HTML
<script>
  try {
    var saved = localStorage.getItem('theme') || 'system';
    var dark = saved === 'dark' || (saved === 'system' && matchMedia('(prefers-color-scheme: dark)').matches);
    document.documentElement.dataset.theme = dark ? 'dark' : 'light';
  } catch (e) {}
</script>

Because the server cannot know the preference, also avoid rendering theme-dependent text (such as "Currently: dark") on the server, or you get a hydration mismatch. Finally, check contrast in both themes; a color that passes on white often fails on dark. See accessibility.

CSS Modules, utility classes and CSS-in-JS

When global CSS starts to hurt, three families of tools solve it differently. None can run in our editor because they need a build step or an npm package, so these blocks are read-only.

CSS Modules turn a stylesheet into a scoped object. The bundler renames every class to something unique, so .title in two files never collides.

JSX
// Card.module.css contains:  .card { ... }  .title { ... }
import styles from './Card.module.css';

export function Card({ title }) {
  return (
    <div className={styles.card}>
      <h3 className={styles.title}>{title}</h3>
    </div>
  );
}

This is plain CSS with local scope: no runtime cost, great performance, and a very small learning curve.

Utility classes (Tailwind CSS) style elements by composing tiny single-purpose classes directly in the markup. A component is then the unit of reuse instead of a CSS class.

JSX
export function Alert({ children }) {
  return (
    <div className="rounded-lg border border-amber-300 bg-amber-50 p-4 text-amber-900">
      {children}
    </div>
  );
}

The stylesheet only contains the utilities you used, so it stays small. The trade-off is long class strings, which you tame by extracting components, not by copy-pasting.

CSS-in-JS libraries (styled-components, Emotion, and zero-runtime tools such as Panda CSS or vanilla-extract) let you write styles in JavaScript. Runtime libraries generate and inject CSS while the app runs, which costs performance and complicates server rendering and React's concurrent features; many teams have moved to build-time or utility approaches. A good default for a new project is CSS Modules or Tailwind. Pick one approach per project and be consistent.

Do not forget accessibility

Style choices affect who can use your UI. Three rules cover most cases.

  1. Never remove focus outlines without replacing them. outline: none makes keyboard navigation impossible to follow. Style :focus-visible instead, which shows the ring for keyboard users but not for mouse clicks.
  2. Keep contrast high enough. Text should have a contrast ratio of at least 4.5:1 against its background, in every theme.
  3. Do not use color alone to convey meaning. The selected tag earlier also sets aria-pressed; error fields should have a message, not just a red border.
Visible keyboard focus with focus-visible

For a longer treatment see Accessibility in React.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which attribute sets the CSS class of an element in JSX?

    JSX attributes map to DOM properties, and the property for the class attribute is className. class is a reserved word in JavaScript.
  2. 2. What does style={{ padding: 16, lineHeight: 1.5 }} produce?

    React adds px to numeric values for most properties, but leaves unitless properties such as lineHeight, opacity and zIndex alone.
  3. 3. Why are inline styles a poor choice for hover effects?

    An inline style object can only set properties on that one element. Pseudo-classes, pseudo-elements, media queries and keyframes need a stylesheet.
  4. 4. What does a CSS Module give you that a plain global stylesheet does not?

    The bundler renames each class to a unique name and hands you a mapping object, so the same class name in two files never clashes.
  5. 5. Which is the best way to show keyboard focus on a button?

    :focus-visible shows the ring for keyboard users without drawing it for mouse clicks. Removing outlines entirely makes keyboard navigation unusable.

Summary

  • Use className (not class) and htmlFor (not for); build class strings from props and state.
  • The style prop takes an object with camelCase keys; numbers become px except for unitless properties.
  • Use inline styles for truly dynamic values and classes for everything else; inline styles cannot do pseudo-classes or media queries.
  • CSS variables set through style connect React state to a normal stylesheet and make theming simple.
  • CSS is global by default; CSS Modules, utility classes (Tailwind) and CSS-in-JS are three ways to avoid collisions. Choose one per project.
  • Keep focus visible with :focus-visible, keep contrast high, and never rely on color alone.

Next: Designing Components