Dynamic styling

2 snippets in React

REReact

Inline Styles

RE · Styling
Syntax
<div style={{ cssProperty: value }} />
Example
function AlertBanner({ type, message }) {
  const styles = {
    padding: '12px 16px',
    borderRadius: '6px',
    fontWeight: 'bold',
    backgroundColor: type === 'error' ? '#fde8e8' : '#e8f5e9',
    color: type === 'error' ? '#c62828' : '#2e7d32',
    border: `1px solid ${type === 'error' ? '#ef9a9a' : '#a5d6a7'}`,
  };

  return <div style={styles}>{message}</div>;
}

Note Inline styles use camelCase property names and string/number values. They cannot handle pseudo-classes (:hover), media queries, or keyframe animations. Best for truly dynamic values that change at runtime.

Conditional Classes

RE · Styling
Syntax
// With clsx or classnames library
import clsx from 'clsx';
<div className={clsx('base', { active: isActive, disabled: isDisabled })} />
Example
// Using the clsx library
import clsx from 'clsx';

function StatusChip({ status }) {
  return (
    <span
      className={clsx('chip', {
        'chip--success': status === 'active',
        'chip--warning': status === 'pending',
        'chip--danger': status === 'error',
        'chip--muted': status === 'inactive',
      })}
    >
      {status}
    </span>
  );
}

// Without a library
function StatusChipManual({ status }) {
  const chipClass = [
    'chip',
    status === 'active' && 'chip--success',
    status === 'error' && 'chip--danger',
  ].filter(Boolean).join(' ');

  return <span className={chipClass}>{status}</span>;
}

Note The clsx library (or classnames) accepts strings, objects, and arrays. Object keys are included when their value is truthy. It is lightweight (~228 bytes) and widely used in the React ecosystem.

Frequently asked questions

How does React handle dynamic styling?
React covers this with 2 copy-ready snippets on this page. The "Inline Styles" snippet in React uses `<div style={{ cssProperty: value }} />`.
Which code does the React example use?
The "Inline Styles" snippet uses `<div style={{ cssProperty: value }} />`, from the Styling section of the React cheat sheet.
What other React snippets are shown for "dynamic styling"?
Besides "Inline Styles", this page also shows "Conditional Classes".
Is there anything to watch out for?
Yes. For "Inline Styles": Inline styles use camelCase property names and string/number values. They cannot handle pseudo-classes (:hover), media queries, or keyframe animations. Best for truly dynamic values that change at runtime.