React - Styling Strategies

Overview

Estimated time: 15–25 minutes

Explore three practical styling approaches in React without a bundler: class-based CSS in a style tag, inline style objects, and a minimal CSS-in-JS pattern.

Try it: Class-based CSS

View source
function ClassDemo(){
  return (
    <div className="demo-card">
      <span className="demo-primary">Primary label</span>
    </div>
  );
}
ReactDOM.createRoot(document.getElementById('try-css-class')).render(<ClassDemo />);

Try it: Inline style objects

View source
function InlineDemo(){
  const card = { padding:12, border:'1px solid var(--border)', borderRadius:10, background:'rgba(148,163,184,.08)' };
  const badge = { color:'#0f172a', background:'#93c5fd', padding:'6px 10px', borderRadius:8, display:'inline-block' };
  return (
    <div style={card}>
      <span style={badge}>Primary label</span>
    </div>
  );
}
ReactDOM.createRoot(document.getElementById('try-inline-style')).render(<InlineDemo />);

Try it: Minimal CSS-in-JS helper

View source
function cx(...parts){ return parts.filter(Boolean).join(' '); }
function JsDemo({ primary }){
  const base = 'demo-card';
  return (
    <div className={base}>
      <span className={cx('demo-primary', primary && 'is-primary')}>Label</span>
    </div>
  );
}
ReactDOM.createRoot(document.getElementById('try-css-js')).render(<JsDemo primary={true} />);

Syntax primer

  • Class-based CSS: use className; keep styles in CSS.
  • Inline styles: camelCased properties and JS objects.
  • CSS-in-JS: class composition helpers or libraries (not shown here) for dynamic styling.

Common pitfalls

  • Overusing inline styles (harder theming, no media queries) – balance approaches.

Checks for Understanding

  1. When might inline styles be a good choice? When are they limiting?
  2. What advantages do CSS classes have over inline styles?
Show answers
  1. Good for dynamic one-off values and quick demos; limiting for media queries, pseudo-selectors, and theming.
  2. Better reuse, theming, and control with the full power of CSS (media queries, variables, cascade).

Exercises

  1. Add a dark mode by toggling a CSS class on a wrapper and updating variables.
  2. Refactor the inline style demo to use CSS variables; switch themes via a class.
  3. Create a helper that conditionally composes classes (cx) and use it across demos.