Sometimes, we want to define CSS variables in style attribute in React and TypeScript.
In this article, we’ll look at how to define CSS variables in style attribute in React and TypeScript.
How to define CSS variables in style attribute in React and TypeScript?
To define CSS variables in style attribute in React and TypeScript, we can create an object of type React.CSSProperties
in our component.
For instance, we write
const App = () => {
//...
const style = { "--my-css-var": 10 } as React.CSSProperties;
return <div style={style}>...</div>;
};
to create the style
variable of type React.CSSProperties
.
Then we can assign that as the value of the style
prop of the div
without compiler errors.
Conclusion
To define CSS variables in style attribute in React and TypeScript, we can create an object of type React.CSSProperties
in our component.