How to define css variables in style attribute in React and typescript
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} />
}
If you go to the definition of CSSProperties
, you'll see:
export interface CSSProperties extends CSS.Properties<string | number> {
/**
* The index signature was removed to enable closed typing for style
* using CSSType. You're able to use type assertion or module augmentation
* to add properties or an index signature of your own.
*
* For examples and more information, visit:
* https://github.com/frenic/csstype#what-should-i-do-when-i-get-type-errors
*/
}
That link gives examples of how to solve the type error by augmenting the definition of Properties
in csstype
or casting the property name to any
.