snippettypescriptreactMajorCanonical
How to define css variables in style attribute in React and TypeScript
Viewed 0 times
variablestypescripthowattributestyleandcssreactdefine
Problem
I want to define jsx like this:
and I use
but typescript throws an error:
is it possible to change the type of style attribute to accept CSS variables (custom properties) or is there a way to force any on the style object?
{array}
and I use
--length in CSS, I also have cells that have --count that shows count using CSS pseudo selector (using the counter hack).but typescript throws an error:
TS2326: Types of property 'style' are incompatible.
Type '{ '--length': number; }' is not assignable to type 'CSSProperties'.
Object literal may only specify known properties, and ''--length'' does not exist in type 'CSSProperties'.is it possible to change the type of style attribute to accept CSS variables (custom properties) or is there a way to force any on the style object?
Solution
Casting the
By extending
Using
style to any defeats the whole purpose of using TypeScript, so I recommend extending React.CSSProperties with your custom set of properties:import React, {CSSProperties} from 'react';
export interface MyCustomCSS extends CSSProperties {
'--length': number;
}By extending
React.CSSProperties, you will keep TypeScript's property checking alive and you will be allowed to use your custom --length property.Using
MyCustomCSS would look like this:const MyComponent: React.FC = (): JSX.Element => {
return (
);
};Code Snippets
import React, {CSSProperties} from 'react';
export interface MyCustomCSS extends CSSProperties {
'--length': number;
}const MyComponent: React.FC = (): JSX.Element => {
return (
<input
style={
{
'--length': 300,
} as MyCustomCSS
}
/>
);
};Context
Stack Overflow Q#52005083, score: 64
Revisions (0)
No revisions yet.