Passing Variables to React style to Change Width and Color
To change a width or color based on a value in React, compute the value, put it in an object, and pass it to style, like style={{ width: `${percent}%`, backgroundColor: color }}. Each time the value changes and the component re-renders, the element's style attribute is rewritten. This pattern works for the length of a progress bar that shows upload or input progress, the length of a chart bar, or colors that change with a remaining amount or stock count.
In a Chromium test environment, I checked what happens to the style attribute when I pass numbers, strings without units, undefined, and CSS variables (custom properties).
The test environment was Ubuntu 24.04 and Node.js 22.23.4. I installed react and react-dom 19.3.1, @types/react 19.3.0, and TypeScript 7.0.2, bundled the code for development with esbuild, and opened it in Chromium 153 driven by Playwright 1.63.0. The components are wrapped in StrictMode. I did not test Next.js or other frameworks, server rendering, CSS-in-JS libraries such as styled-components, or browsers other than Chromium.
- 1. Calculating the width and color from state and passing them to style
- 2. Numbers get px, but opacity and lineHeight do not
- 3. A unitless string is ignored by the browser
- 4. Passing undefined removes only that property
- 5. Write property names in camelCase
- 6. Passing CSS variables keeps the visual styling in CSS
Calculating the width and color from state and passing them to style
In the following component, the percent value sets the width of the bar, and the color changes depending on the value.
import { useState } from 'react';
// Change the bar color depending on the value
function barColor(percent: number): string {
if (percent >= 80) return '#e5484d';
if (percent >= 50) return '#f0a020';
return '#00c8e8';
}
export default function ProgressBar() {
const [percent, setPercent] = useState(30);
return (
<div>
<div className="track">
<div
data-testid="bar"
style={{ width: `${percent}%`, backgroundColor: barColor(percent) }}
/>
</div>
<p>{percent}%</p>
<button onClick={() => setPercent((p) => Math.min(p + 10, 100))}>+10%</button>
<button onClick={() => setPercent((p) => Math.max(p - 10, 0))}>-10%</button>
</div>
);
}
The outer curly braces in style={{ ... }} are the JSX syntax for embedding a JavaScript value, and the inner curly braces are an ordinary object. The official reference's section on applying CSS styles also explains that style={{}} is not a special syntax, just an object written inside JSX curly braces.
I applied the following CSS to the outer track and the bar.
.track{width:300px;height:16px;background:#e6eef1;border-radius:8px;overflow:hidden}
.track > div{height:100%}
When the page opened, the bar's style attribute was width: 30%; background-color: rgb(0, 200, 232);. The outer track (.track) is 300px wide, so the actual width of the bar was 90px. Each press of "+10%" rewrote the attribute. At 50%, the bar turned orange (rgb(240, 160, 32)), and at 80%, it turned red (rgb(229, 72, 77)). At 80%, the width was 240px.

Splitting the color logic into a function such as barColor keeps the JSX easier to read.
The official reference's description of style says to use it only for dynamic styles whose values are not known in advance, and that for everything else, applying a CSS class with className is more efficient. I kept values that never change, such as the corner radius and height of the bar, in CSS, and passed only the width and color, which change with the value, through style.
Numbers get px, but opacity and lineHeight do not
You can pass either strings or numbers as values. When you pass a number, React adds px.
// Pass numbers as they are
export default function Numbers() {
const size = 120;
return (
<div
data-testid="numbers"
style={{ width: size, height: size / 2, margin: 0, opacity: 0.5, lineHeight: 1.5, zIndex: 2, flexGrow: 1 }}
/>
);
}
The style attribute of this element was as follows.
width: 120px; height: 60px; margin: 0px; opacity: 0.5; line-height: 1.5; z-index: 2; flex-grow: 1;
width and height got px, while opacity, lineHeight, zIndex, and flexGrow stayed as plain numbers. The official reference also states that numbers get px for every property except unitless ones. In the development build of react-dom 19.3.1, there is a list of unitless properties, including fontWeight, opacity, order, zIndex, flex, flexGrow, flexShrink, aspectRatio, scale, zoom, gridRow, and gridColumn.
When I passed 1.5 to lineHeight, it was kept as 1.5 and not turned into 1.5px. As the MDN page on line-height explains, a unitless number is treated as a multiplier of the element's font size.
A unitless string is ignored by the browser
px is added only when the value is a number. If you pass the string '120', no px is added.
// Wrong: passing a unitless string to width
export default function NoUnit() {
const size = '120';
return <div data-testid="no-unit" style={{ width: size, height: 20 }} />;
}
The style attribute of this element contained only height: 20px;, and there was no width. As the MDN page on the length (<length>) type explains, the unit can be omitted in CSS lengths only for 0, so the browser rejected 120. The actual width stayed at the full width of the parent element.
The type of width also accepts strings, so the tsc type check did not report an error. When you use a number received as a string, such as an input field value or a URL parameter, for a width, either convert it with Number(size) before passing it, or add a unit, as in `${size}px`.
Passing undefined removes only that property
To add or remove a color depending on a condition, pass undefined for the case where you want to remove it.
import { useState } from 'react';
// Whether the style attribute drops the property when the value goes back to undefined
export default function Toggle() {
const [on, setOn] = useState(true);
return (
<div>
<div data-testid="toggle" style={{ color: 'black', backgroundColor: on ? '#eefafd' : undefined }} />
<button data-testid="toggle-btn" onClick={() => setOn((v) => !v)}>切り替え</button>
</div>
);
}
The first style attribute was color: black; background-color: rgb(238, 250, 253);. After I pressed the toggle button, it became only color: black;, and the background color was removed. Pressing the button again brought the background color back. In the development build of react-dom, when the value is null, undefined, a boolean, or an empty string, React clears that property.
Write property names in camelCase
In a style object, write names in camelCase, such as backgroundColor instead of background-color. That is, remove the hyphen and capitalize the next letter. I also tested what happens when you use the same hyphenated names as CSS.
// Wrong: written with hyphenated names like CSS
export default function Kebab() {
return <div data-testid="kebab" style={{ 'background-color': '#00c8e8', height: 20 }} />;
}
In Chromium, the background color was applied, but the console showed the following error. I filled in the name where %s appears.
Unsupported style property background-color. Did you mean backgroundColor?
The type check also reported an error.
src/ng/Kebab.tsx(3,44): error TS2353: Object literal may only specify known properties, and ''background-color'' does not exist in type 'Properties<string | number, string & {}>'.
If you write the style as a string, as in HTML, like style="width: 120px", tsc reports the error TS2559. In the browser, React throws an error during rendering, and the element is not displayed.
The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX.
Passing CSS variables keeps the visual styling in CSS
If you want to keep the rules for widths and colors in CSS and pass only the values from React, pass CSS variables (custom properties) through style. On the CSS side, only read the variables, as shown below.
.swatch {
width: var(--swatch-size);
height: var(--swatch-size);
background: var(--swatch-color);
}
In a style object, write names that start with -- as they are. However, numbers passed for these names do not get px.
import type { CSSProperties } from 'react';
// Pass CSS variables (custom properties) via style
export default function CustomProp({ color, size }: { color: string; size: number }) {
return (
<div
data-testid="custom"
className="swatch"
style={{ '--swatch-color': color, '--swatch-size': size } as CSSProperties}
/>
);
}
When I passed 40 as size, the style attribute was --swatch-color: #067a98; --swatch-size: 40;. The color was applied, but width: var(--swatch-size) became the unitless 40, which is not a valid width. The element was full width with a height of 0, so no square was visible. In the development build of react-dom, names starting with -- are passed to setProperty() as they are.
When I passed the value with a unit, as in '--swatch-size': `${size}px`, the style attribute became --swatch-size: 40px;, and a 40px square was displayed.
React adds px to CSS properties such as width: 40, but not to CSS variables. When you pass a length through a CSS variable, use a string with a unit.
Making TypeScript accept CSS variable names
When I removed as CSSProperties from the code above, the type check reported the following error.
src/ng/CustomNoCast.tsx(3,52): error TS2353: Object literal may only specify known properties, and ''--swatch-color'' does not exist in type 'Properties<string | number, string & {}>'.
In @types/react, CSSProperties is defined as interface CSSProperties extends CSS.Properties<string | number>. The Properties<…> in the error message is the type this is based on. Since this type has no --swatch-color name, the error occurs.
Adding as CSSProperties removes the error, but you won't notice if you misspell a name. tsc also passed without errors for code with a typo such as { '--swach-color': color } as CSSProperties. If you know which CSS variables you use, you can add their names to the CSSProperties type from react.
// css-vars.d.ts
import 'react';
// Add the CSS variables used in this app as names that can be written in style
declare module 'react' {
interface CSSProperties {
'--swatch-color'?: string;
'--swatch-size'?: string;
}
}
After I included this file in the type check, style={{ '--swatch-color': color, '--swatch-size': `${size}px` }} passed without as. On the other hand, a line with the typo '--swach-color' produced the following error.
src/aug/Typo.tsx(3,43): error TS2353: Object literal may only specify known properties, and ''--swach-color'' does not exist in type 'CSSProperties'.
Because I typed '--swatch-size' as string, a line that passes the number as is, like style={{ '--swatch-size': size }}, also got the error Type 'number' is not assignable to type 'string'. (TS2322). The missing unit I mentioned earlier can also be caught by the type check.





