Thuta Learning
React
AdvancedWeb DevelopmentIntermediate

Styling in React

ReactLesson 2425 min

What you'll walk away with

  • Explain why JSX uses className instead of class and a style object instead of a style string
  • Choose between plain CSS, CSS Modules, utility classes and CSS-in-JS by scope and fit
  • Build a className conditionally from props
  • Pass dynamic values to CSS through a custom property such as --progress

Explain it simply

Explain it simply

React does not invent a new way to style things. In the end the browser still sees plain HTML elements and CSS. React's job is to attach a class name or an inline style to each element from inside your components.

Think of a wardrobe. Plain CSS is one big wardrobe the whole family shares. CSS Modules are a personal drawer for each person, so two shirts with the same name never get mixed up. An inline style is like pinning a badge directly onto today's outfit.

Problem → Why → Solution

The problem: HTML habits and global class collisions

A developer coming from HTML writes the Card component below. class="title" triggers an "Invalid DOM property class" warning in the development console. style="color: navy" is worse: React does not accept a string style and throws an error while rendering.

Even after fixing those, one problem remains. Both Card.css and Modal.css define .title. Imported CSS files are global to the whole app, so whichever rule loads later wins everywhere, and the card's title suddenly shrinks.

Card.jsx
// Card.css:  .title { font-size: 24px; }
// Modal.css: .title { font-size: 14px; }   <- also global!
import './Card.css';

export function Card() {
  return (
    <h2 class="title" style="color: navy">  {/* warning + render error */}
      Monthly report
    </h2>
  );
}

Why does this happen?

JSX is JavaScript, so it uses DOM property names. In the DOM, the property for the class attribute is className, and style is an object of CSS properties. Importing a CSS file inside a component does not mean "only for this component". The bundler simply adds it to the page, so every selector applies to the whole document.

Core concept: how styles reach the DOM

Every styling approach in React ends up producing one of two things: a class name on the element, or an inline style. What differs is who invents the class names and how far the CSS rules reach, which is called scope.

ApproachScopeGood fit
Plain CSS fileGlobal, the whole documentSmall apps, resets and base styles
CSS Modules (*.module.css)Per file; class names made uniqueComponent styles without a library
Utility classes (Tailwind)Each class is one tiny ruleFollowing one design system quickly
CSS-in-JS (styled-components, etc.)Per componentTheme-heavy JS logic; extra setup for server rendering
style={{ ... }}One element onlyOne-off dynamic values

1. className takes a single string

Several classes are joined with spaces. To vary them by prop, use a template literal such as `btn btn--${variant}` or a small helper like clsx.

2. style is a camelCase object

background-color becomes backgroundColor. For most properties React adds px to plain numbers, so padding: 16 becomes padding:16px, while unitless properties such as lineHeight: 1.5 stay as they are.

3. Send dynamic values through CSS variables

Writing style={{ '--progress': '40%' }} puts a custom property on the element, and width: var(--progress) in the CSS file reads it. The rules stay in CSS and only the value comes from JavaScript.

4. Know inline style's limits

Pseudo-classes such as :hover and :focus-visible, and media queries, cannot be written in an inline style. When you need them, use a class.

A practical rule of thumb: start each component with a CSS file and className. Move to CSS Modules when names start to collide, and keep inline styles for values only JavaScript knows, such as a measured width or a colour the user picked.

Mental model: who owns the class name?
  1. The component picks a className
  2. A CSS rule matches that class
  3. Scope decides how far the rule reaches
  4. Dynamic values enter via style or var()

For every styling choice, first ask which elements this rule can touch. If the answer is "all of them", plan for name collisions up front.

General pattern

jsx
import './Component.css';                 // global rules
import styles from './Part.module.css';   // scoped rules

<div className="block block--variant" />;
<div className={styles.part} />;
<div className={`base ${isActive ? 'base--active' : ''}`} />;
<div style={{ marginTop: 8, '--size': `${value}px` }} />;

Four shapes: import global CSS and use a string class, take a class from a CSS Module object, build a class conditionally, and pass a style object with a CSS variable.

Connecting a CSS file with className

Here is the simplest approach: one CSS file and a className. The example shows the contents of App.css as comments; in a real project it is a separate file next to the JSX file. When a bundler such as Vite sees import './App.css', it adds that CSS to the page.

jsx
// App.jsx
import './App.css';

function AlertBox() {
  return (
    <div className="alert-box">
      <strong>Tip:</strong> Keep component styles in a separate CSS file.
    </div>
  );
}

// App.css
// .alert-box {
//   padding: 16px;
//   border-radius: 12px;
//   background: #eef6ff;
//   color: #102033;
// }

Code breakdown

  1. Import the stylesheetimport './App.css';

    Nothing is imported as a value; it tells the bundler to include this CSS on the page. Once included, its rules are global.

  2. className, not class<div className="alert-box">

    JSX uses the DOM property name className; in the browser it becomes the attribute class="alert-box".

  3. Rule that matches the class// .alert-box {

    The .alert-box selector matches every element with that class. If another component anywhere in the app uses alert-box, it gets this style too.

  4. Visual details// border-radius: 12px;

    Padding, rounded corners, background and text colour live in CSS, so the component code only cares about structure.

You should see
A tip box appears with padding, rounded corners, and a background color.

Fixing collisions with CSS Modules

If a file name ends in .module.css, like Button.module.css, Vite and most frameworks rewrite its class names to be unique per file. The imported styles object maps the name you wrote (styles.primary) to the real generated class. So Card.module.css and Modal.module.css can both define .title without colliding.

Button.jsx
// Button.module.css
// .button { padding: 8px 16px; border-radius: 8px; }
// .primary { background: #2563eb; color: white; }
import styles from './Button.module.css';

export function Button({ variant = 'default', children }) {
  const className = variant === 'primary'
    ? `${styles.button} ${styles.primary}`
    : styles.button;
  return <button className={className}>{children}</button>;
}

Utility classes and complete class names

With a utility-first framework such as Tailwind, you write little CSS by hand and instead combine small classes like p-4, rounded-xl and bg-blue-50 in className. The build tool scans your source files and generates CSS only for classes that actually appear.

That is why you should not assemble class names from pieces, as in `bg-${color}-50`. The scanner never sees the complete name in your code, so no CSS is generated for it. Write each variant's full class string in an object, as in the example below.

Alert.jsx
const TONES = {
  info: 'bg-blue-50 text-blue-900',
  error: 'bg-red-50 text-red-900',
};

export function Alert({ tone = 'info', children }) {
  return (
    <div role="status" className={`rounded-xl p-4 ${TONES[tone]}`}>
      {children}
    </div>
  );
}

In real projects

In real projects

Most teams pick one approach and use it consistently across the project. For example, global CSS only for resets, fonts and colour variables, and every component style in CSS Modules or Tailwind. Mixing styles freely makes "where does this button's colour come from?" hard to answer.

Defining colours, spacing and radii as CSS custom properties such as --color-primary on :root means dark mode is just a matter of redefining those variables. Design teams often hand developers named tokens instead of raw hex codes, and those tokens map directly onto such variables. In frameworks built on Server Components, some runtime CSS-in-JS libraries need extra setup, so teams increasingly prefer approaches that emit static CSS. Check the library's current documentation before choosing.

Common mistakes

Common mistakes

Writing style as a string

style="color: red" makes React throw "The style prop expects a mapping from style properties to values, not a string", and the component does not render. Use an object: style={{ color: 'red' }}.

Generic class names in plain CSS

Names like .title, .card and .active collide between components very easily in global CSS. If you stay with plain CSS, prefix them with the component name, such as .report-card__title, or switch to CSS Modules.

Looking for hover in inline styles

Adding a ':hover' key to a style object does nothing. Rather than tracking hover with useState, use a class with CSS :hover, which is simpler and lets you add :focus-visible for keyboard users too.

Mini challenge

A StatusBadge and a ProgressBar

Write two components. StatusBadge switches its class by the status prop and falls back to a neutral style for unknown statuses. ProgressBar clamps its value to 0-100 and shows the width through a --progress CSS variable.

  • Build StatusBadge's className, such as "badge badge--success", with a template literal
  • Treat any status other than success, warning and error as neutral
  • Clamp ProgressBar's value so it is never below 0 or above 100
  • Add role="progressbar", aria-valuenow/min/max and an aria-label
Indicators.jsx
// styles.css
// .badge--success, .badge--warning, .badge--error, .badge--neutral { ... }
// .progress__fill { width: var(--progress); }

const STATUSES = ['success', 'warning', 'error'];

export function StatusBadge({ status, children }) {
  // TODO: pick the variant (unknown -> 'neutral')
  // TODO: <span> with className "badge badge--<variant>"
}

export function ProgressBar({ value, label }) {
  // TODO: clamp value to 0..100
  // TODO: outer div with role + aria attributes
  // TODO: inner div whose style sets '--progress' to "<percent>%"
}

Expected: <StatusBadge status="success"> renders class="badge badge--success" and status="unknown" renders badge--neutral. <ProgressBar value={130}> outputs aria-valuenow="100" and style="--progress:100%".

Show hint

Math.min(100, Math.max(0, value)) is enough for the clamp. A CSS variable name contains dashes, so write '--progress' as a quoted key in the style object.

Show solution
Indicators.jsx
// styles.css
// .badge { padding: 2px 8px; border-radius: 999px; font-size: 12px; }
// .badge--success { background: #dcfce7; color: #166534; }
// .badge--warning { background: #fef9c3; color: #854d0e; }
// .badge--error { background: #fee2e2; color: #991b1b; }
// .badge--neutral { background: #e5e7eb; color: #374151; }
// .progress { height: 8px; background: #e5e7eb; border-radius: 4px; }
// .progress__fill { width: var(--progress); height: 100%; background: #2563eb; }
import './styles.css';

const STATUSES = ['success', 'warning', 'error'];

export function StatusBadge({ status, children }) {
  const variant = STATUSES.includes(status) ? status : 'neutral';
  return <span className={`badge badge--${variant}`}>{children}</span>;
}

export function ProgressBar({ value, label }) {
  const percent = Math.min(100, Math.max(0, value));
  return (
    <div
      className="progress"
      role="progressbar"
      aria-label={label}
      aria-valuemin={0}
      aria-valuemax={100}
      aria-valuenow={percent}
    >
      <div className="progress__fill" style={{ '--progress': `${percent}%` }} />
    </div>
  );
}

export default function Demo() {
  return (
    <>
      <StatusBadge status="success">Deployed</StatusBadge>
      <StatusBadge status="unknown">Draft</StatusBadge>
      <ProgressBar value={130} label="Upload progress" />
    </>
  );
}

Quick quiz 1 / 3

What happens if a React component renders <p style="color: red">Hi</p>?

Quick quiz 2 / 3

Which style attribute does <div style={{ padding: 16, lineHeight: 1.5 }} /> produce in HTML?

Quick quiz 3 / 3

Card.css and Modal.css both define .title and one overrides the other. What is the simplest fix that needs no extra library?

What to remember

  • JSX uses className (a string) and style (a camelCase object)
  • Imported plain CSS is global, so class names can collide
  • CSS Modules make class names unique per file
  • Pass dynamic values as --name CSS variables and keep the rules in CSS
  • Pick one styling approach per project and use it consistently

React Documentation — React

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Styling in React | Thuta Learning