TExcelTAD
Home › React › React Styling

React Styling

React doesn't force a styling approach on you. Anything that produces CSS works, and real projects mix several techniques. This lesson covers the most common ones: inline styles, CSS classes, CSS Modules, and utility frameworks.

Inline styles

The style prop takes a JavaScript object. Property names are camelCase (backgroundColor, not background-color), and numbers are treated as pixels for size properties:

jsx · try it yourself
export default function App() {
  const card = {
    backgroundColor: '#282c34',
    color: '#61dafb',
    padding: 20,           // "20px"
    borderRadius: 12,
    fontSize: 20,
    width: 260,
    boxShadow: '0 4px 12px rgba(0,0,0,0.2)',
  };

  return (
    <div style={card}>
      <div style={{ fontSize: 40 }}>⚛️</div>
      Styled with a JavaScript object
    </div>
  );
}

Inline styles are great for dynamic values computed from state:

jsx · try it yourself
import { useState } from 'react';

export default function App() {
  const [progress, setProgress] = useState(40);
  const color = progress < 30 ? '#e74c3c' : progress < 70 ? '#f39c12' : '#27ae60';

  return (
    <div style={{ width: 300 }}>
      <div style={{ background: '#eee', borderRadius: 8, overflow: 'hidden', height: 24 }}>
        <div style={{ width: `${progress}%`, height: '100%', background: color, transition: 'width 0.3s, background 0.3s' }} />
      </div>
      <p>{progress}% complete</p>
      <button onClick={() => setProgress(Math.max(0, progress - 10))}>−10</button>{' '}
      <button onClick={() => setProgress(Math.min(100, progress + 10))}>+10</button>
    </div>
  );
}

Limitations: inline styles can't express pseudo-classes (:hover), media queries or keyframe animations.

CSS classes with className

For anything static, regular CSS with className is usually better. In a Vite project you import './App.css' in a component; in the playground we can put the CSS in a <style> element:

jsx · try it yourself
import { useState } from 'react';

const css = `
  .btn { padding: 8px 16px; border: none; border-radius: 6px; cursor: pointer; font-size: 15px; margin-right: 6px; }
  .btn:hover { filter: brightness(1.1); }
  .btn-primary { background: #1677ff; color: white; }
  .btn-danger { background: #ff4d4f; color: white; }
  .btn-ghost { background: transparent; border: 1px solid #999; }
  .btn.active { outline: 3px solid gold; }
`;

function Button({ variant = 'primary', active, children, onClick }) {
  const classes = ['btn', `btn-${variant}`, active && 'active'].filter(Boolean).join(' ');
  return <button className={classes} onClick={onClick}>{children}</button>;
}

export default function App() {
  const [selected, setSelected] = useState('primary');
  return (
    <div>
      <style>{css}</style>
      {['primary', 'danger', 'ghost'].map((v) => (
        <Button key={v} variant={v} active={selected === v} onClick={() => setSelected(v)}>
          {v}
        </Button>
      ))}
    </div>
  );
}

Building class strings with [...].filter(Boolean).join(' ') is a common trick; many projects use the tiny clsx library for the same job.

CSS Modules

Global class names can clash in big apps. CSS Modules — supported by Vite out of the box — scope class names to one file. Name the file *.module.css and import it as an object:

css
/* Button.module.css */
.primary { background: #1677ff; color: white; }
.large { font-size: 20px; }
jsx
import styles from './Button.module.css';

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

At build time styles.primary becomes a unique name like Button_primary_x7f2a, so it can never collide with a .primary class in another file.

Utility-first CSS (Tailwind)

Tailwind CSS provides tiny single-purpose classes that you combine directly in JSX:

jsx
<button className="rounded-lg bg-sky-600 px-4 py-2 font-semibold text-white hover:bg-sky-700">
  Save
</button>

CSS variables for theming

Custom properties work beautifully with React: set them through style, consume them in CSS.

jsx · try it yourself
import { useState } from 'react';

const css = `
  .theme { background: var(--bg); color: var(--fg); padding: 16px; border-radius: 10px; transition: all .3s; width: 280px; }
  .theme button { background: var(--accent); color: var(--bg); border: none; padding: 6px 12px; border-radius: 6px; }
`;

const THEMES = {
  light: { '--bg': '#ffffff', '--fg': '#222222', '--accent': '#6c5ce7' },
  dark: { '--bg': '#1e1e2e', '--fg': '#cdd6f4', '--accent': '#f9e2af' },
};

export default function App() {
  const [mode, setMode] = useState('light');
  return (
    <div className="theme" style={{ ...THEMES[mode], border: '1px solid #ccc' }}>
      <style>{css}</style>
      <p>Current theme: {mode}</p>
      <button onClick={() => setMode(mode === 'light' ? 'dark' : 'light')}>Toggle theme</button>
    </div>
  );
}

Which approach should I use?

Approach Strengths Weaknesses
Inline style dynamic values, no setup no :hover, media queries; verbose
Global CSS + className familiar, full CSS power name collisions in large apps
CSS Modules scoped names, plain CSS one extra file per component
Tailwind fast to write, consistent design long class strings
CSS-in-JS libraries styles colocated with logic runtime cost, extra dependency

Tip: A good default: CSS Modules or Tailwind for static styles, plus inline style (or CSS variables) for values that depend on state.

Test yourself

How do you write background-color: red as an inline style in JSX?

  1. style="background-color: red"
  2. style={{ backgroundColor: 'red' }}
  3. style={{ 'background-color': red }}
  4. css={{ background: red }}

What does style={{ width: 200 }} produce?

  1. width: 200
  2. width: 200px
  3. width: 200%
  4. An error: units are required

Which problem do CSS Modules solve?

  1. Missing hover styles
  2. Global class name collisions
  3. Slow JavaScript
  4. Browser compatibility of flexbox