Categories
TypeScript Answers

How to define CSS variables in style attribute in React and TypeScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *