Like this:
function Component() {
const style = { "--my-css-var": 10 } as React.CSSProperties;
return <div style={style}>...</div>
}
Or without the extra style variable:
function Component() {
return <div style={{ "--my-css-var": 10 } as React.CSSProperties} />
}
Answer from ixrock on Stack OverflowLike this:
function Component() {
const style = { "--my-css-var": 10 } as React.CSSProperties;
return <div style={style}>...</div>
}
Or without the extra style variable:
function Component() {
return <div style={{ "--my-css-var": 10 } as React.CSSProperties} />
}
This works in both .tsx files and .d.ts files.
The key is to include import 'react' at the top. This turns the file into a module (even if it is a .d.ts file), allowing you to use Module Augmentation to extend the existing React types rather than overwriting them.
The Solution
Place this snippet at the top of your component file (.tsx) or in any definition file (e.g., types.d.ts).
import 'react';
declare module 'react' {
interface CSSProperties {
// Allow any CSS variable starting with '--'
[key: `--${string}`]: string | number
}
}
Usage
Now you can pass CSS variables to the style prop without TypeScript errors:
<div style={{ "--value": percentage, color: "var(--value)" }} />
How can I use dynamic css variables in react?
Inline CSS Variables
reactjs - update CSS variables in React dynamically? - Stack Overflow
Help with dynamic CSS properties with JS/React? How come 1 of these 2 examples don't work?
Videos
I am trying to create a component that sets CSS Variables using the inline style attribute. Example:
<div style={{'--item-color': props.color}}>...</div>
Is this possible with react? I can't find any documentation or previous conversation on the topic. All I can find is using DOM CSS properties like backgroundColor: ....
The above example would give the following error:
Type '{ '--item-color': string; }' is not assignable to type 'Properties<string | number, string & {}>'.Object literal may only specify known properties, and ''--item-color'' does not exist in type 'Properties<string | number, string & {}>'.ts(2322)