Sub topic 11
Passing dynamic values with CSS custom properties
This chapter assumes you can write React function components, know how to import a .module.css file and apply styles.someClass, and understand the CSS cascade. Earlier chapters showed how to switch between a fixed set of classes. Here you will handle values that are not known until runtime, such as a progress percentage, a user-chosen color, or a measured height.
The problem: values that cannot be a class
CSS Modules work well when the possible styles are a short, known list. A button is primary or secondary. A card is compact or roomy. You write one class per option and pick one in the component.
Some values have no short list. A progress bar can be at any whole number from 0 to 100. A color picker can return any hex string. Writing 101 classes for the bar is not practical, and writing a class for each possible color is impossible.
The usual first attempt is to put the value in an inline style:
<div className={styles.bar} style={{ width: `${value}%` }} />This works, but it moves a styling decision out of the stylesheet. The component now knows that the bar's width is the thing that changes. Hover states, media queries, and transitions that depend on the value become hard to write, because inline styles cannot contain selectors or media queries.
CSS custom properties give a cleaner split. The component supplies only the data. The stylesheet decides how to use it.
What a custom property is
A custom property is a CSS variable whose name starts with two dashes, such as --progress. You read it with the var() function. Custom properties follow the normal cascade and inheritance rules, so a value set on an element is visible to that element and all of its descendants.
Here is the stylesheet half of a progress bar:
.bar {
width: var(--progress);
height: 8px;
background: #16a34a;
}The .bar class reads --progress but never defines it. Whoever renders the element is responsible for setting it. If nothing sets it, width becomes invalid at computed-value time and the browser treats it as unset, which for width means auto.
Custom property names are not renamed by CSS Modules. Only class names (and a few other identifiers, such as @keyframes names) are made local. --progress stays --progress in the final CSS. This matters, and we return to it in the pitfalls section.
Setting the property from React
React's style prop accepts an object. For a name that starts with --, React calls style.setProperty on the DOM element, so custom properties work in plain JavaScript:
import styles from './Progress.module.css';
export function Progress({ value }) {
return (
<div
className={styles.bar}
style={{ '--progress': `${value}%` }}
/>
);
}The value must be a string (or a number for properties that accept unitless numbers). Build the unit into the string, as in ` ${value}% , or move the unit into the stylesheet with calc()`, which we cover below.
When value changes, React updates the single custom property on the existing element. It does not create a new class, and the browser recomputes only the styles that depend on that property.
The TypeScript cast
In TypeScript, the style prop is typed as CSSProperties. That type lists the standard CSS properties and has no index signature for names like --progress, so the object literal above fails to compile. The usual fix is a cast:
import type { CSSProperties } from 'react';
import styles from './Progress.module.css';
export function Progress({ value }: { value: number }) {
return (
<div
className={styles.bar}
style={{ '--progress': `${value}%` } as CSSProperties}
/>
);
}The cast silences the compiler for the whole object, so a typo in a standard property name inside the same object would also go unnoticed. If you set several custom properties in many components, define a small helper type once:
import type { CSSProperties } from 'react';
type CustomProps = CSSProperties & Record<`--${string}`, string | number>;
export function Swatch({ color, size }: { color: string; size: number }) {
const style: CustomProps = {
'--swatch-color': color,
'--swatch-size': `${size}px`,
borderRadius: 4,
};
return <span style={style} />;
}Here the template-literal key type accepts any name that begins with --, while ordinary properties are still checked.
How the pieces fit together
The class name is fixed at build time. The value is set at runtime. The two meet in the browser through the cascade.
Doing more in the stylesheet
Because the stylesheet owns the logic, you can derive several values from one input and keep the component small.
.bar {
--progress: 0;
width: calc(var(--progress) * 1%);
height: 8px;
background: #16a34a;
transition: width 200ms ease-out;
}
.bar[data-complete='true'] {
background: #15803d;
}
@media (prefers-reduced-motion: reduce) {
.bar {
transition: none;
}
}Three things changed from the earlier version:
- The component can now pass a plain number, such as
'--progress': value. The stylesheet multiplies it by1%. - The line
--progress: 0;inside.baris a default. An inline style on the element has higher priority than a class rule, so the value from React wins whenever it is set. - A transition and a media query are possible because they live in CSS.
The component for this version:
import styles from './Progress.module.css';
export function Progress({ value }) {
const clamped = Math.min(100, Math.max(0, value));
return (
<div
className={styles.bar}
data-complete={clamped === 100}
style={{ '--progress': clamped }}
/>
);
}Clamping in JavaScript is a good habit. CSS does not validate the number for you, and calc(150 * 1%) would draw a bar wider than its container.
Scoping custom properties
Custom properties inherit, which is both useful and risky. Setting a property on a parent lets every child read it:
.theme {
background: var(--surface);
color: var(--text);
}
.title {
color: var(--accent, #2563eb);
}import styles from './Panel.module.css';
export function Panel({ accent, children }) {
return (
<section className={styles.theme} style={{ '--accent': accent }}>
<h2 className={styles.title}>Report</h2>
{children}
</section>
);
}The second argument to var() is a fallback. It applies when the property is not defined, so .title still has a color if accent is not provided. Note that if you pass undefined as the value in React, the property is simply not set, and the fallback is used. If you pass an empty string, React removes the property in the same way.
Inheritance means a nested component can accidentally read a property meant for an ancestor. If two unrelated components both read --size, whichever ancestor sets it closest wins. Prefix names with the component, such as --progress-value or --panel-accent, to avoid collisions. CSS Modules do not do this for you.
Choosing between classes, data attributes, and custom properties
| Situation | Best fit | Why |
|---|---|---|
| A short, fixed set of options (size, tone) | Classes through `styles[variant]` | Each option is visible in the stylesheet and can be searched for |
| A boolean state that CSS should react to | Class or `data-*` attribute | Selectors such as `[data-complete='true']` stay in CSS |
| A continuous or unbounded value (percent, color, pixel offset) | Custom property | One rule handles every value |
| A value needed by `calc()`, gradients, or transitions | Custom property | The browser can combine it with other CSS |
| Many elements need the same runtime value | Custom property on a common ancestor | Set once and inherit |
Pitfalls and edge cases
- Missing unit.
'--progress': 40withwidth: var(--progress)is invalid, because40is not a length. Either include the unit in the value or usecalc(var(--progress) * 1%). - Animating the property itself. A transition on
widthworks as shown. A transition on--progressdoes not animate unless the property is registered with@property, since the browser treats unregistered custom properties as plain text. Registering is global, so it does not fit the module scope well. Prefer transitioning a real property. - Server rendering. Inline custom properties are part of the HTML that the server sends, so there is no flash of unstyled content. This is a reason to prefer them over measuring the DOM and applying styles in an effect.
- Too many inline styles. Setting a property on thousands of list items creates thousands of style attributes. Set it on a shared ancestor when the value is shared.
- Security. A value from a user is placed into a style attribute. React sets it through the DOM API, so it cannot break out into other markup, but an unexpected value can still produce a broken layout. Validate or clamp numbers, and check colors against an allowed format if the source is untrusted.
Summary of the pattern
- Write the class in the
.module.cssfile and read a custom property withvar(). - Give the property a default or a fallback so the class works when the component forgets to set it.
- Set the property in the component through the
styleprop, as a string with a unit or as a number that the stylesheet converts. - In TypeScript, cast the style object or use a helper type that accepts keys starting with
--. - Prefix property names to avoid inheritance collisions.
Exercise
A Badge component receives a hue prop (a number from 0 to 360). Write the CSS Module rule and the JSX so the background color follows hue, with a gray fallback when hue is not provided. Why is --badge-hue a better name than --hue?
Show answer
CSS: .badge { background: hsl(var(--badge-hue, 0) 0% 85%); } is one option for the gray fallback, but a clearer form is .badge { --badge-saturation: 70%; background: hsl(var(--badge-hue) var(--badge-saturation) 85%); } .badgeNeutral { background: #e5e7eb; } combined with a class chosen when hue is undefined. A simple complete answer: .badge { background: hsl(var(--badge-hue, 0) 0% 85%); } renders gray when the property is unset, because saturation 0% always gives gray, and .badge[data-colored='true'] { background: hsl(var(--badge-hue) 70% 85%); } applies the hue when present. JSX: <span className={styles.badge} data-colored={hue !== undefined} style={hue !== undefined ? { '--badge-hue': hue } : undefined}>{children}</span>. The name --badge-hue is better because custom properties are not renamed by CSS Modules and they inherit, so a generic --hue set on an ancestor could be read by this component, or this component could override a value another component expects.
Exercise
A TypeScript component writes style={{ '--progress': '50%' }} and the compiler reports an error. Give two ways to fix it and one drawback of the simpler one.
Show answer
Cast the object with as CSSProperties, or declare a type such as CSSProperties & Record<--${string}, string | number> and annotate the style object with it. The cast is simpler but disables checking for the whole object, so a misspelled standard property in the same object is not reported.