Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extending react style prop with typescript

What is the best way to extend the style prop in react to accept css variables as keys?

<button style={{ "--color": "red", ...props.style }} />
like image 253
Sam Avatar asked Jan 24 '26 09:01

Sam


2 Answers

You'll need to add to the CSSProperties interface, which can be done pretty easily like so

declare module "react" {
  interface CSSProperties {
    /**
     * Add your custom properties here
     */
    "--x": string | number;
  }
}

like image 198
C Sinclair Avatar answered Jan 26 '26 22:01

C Sinclair


You can do the following:

 render() {
   var style = {  "--color": "red", ...props.style } as React.CSSProperties;
   return (<button style={style} />);
  }

More in React.CSSProperties type definition: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/8871b1e8938a1ed698ec8a88c77ee169294e45d4/types/react/index.d.ts#L974-L983

like image 42
Kanishk Anand Avatar answered Jan 26 '26 22:01

Kanishk Anand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!