3

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

<button style={{ "--color": "red", ...props.style }} />

2 Answers 2

4

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;
  }
}

Sign up to request clarification or add additional context in comments.

1 Comment

I get random erros when I do this, like TS complaining a props type that extends HTMLProps<'div'> not having a member called className. Ever seen something like that?
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.