Home > Software engineering >  How to set css variable using react
How to set css variable using react

Time:06-04

how to set css variable in react typescript if I'm trying to

 <main style={{ "--nav-height": navHeight }}>
  </main>
main {
  height: calc(100vh -var(--nav-height));
  background: green;
}

I'm getting

Type '{ "--nav-height": string; }' is not assignable to type 'Properties<string | number, string & {}>'.

CodePudding user response:

In TypeScript, React's style property types are mapped to actual CSS properties (minHeight => min-height, etc).

Since you are entering an unknown property, it fails the type check.

What you can do is assert the type yourself so this doesn't happen anymore.

Method 1

You can set the property name to be any, thus skipping this property when checked:

<main style={{ ["--nav-height" as any]: navHeight }}>

Method 2

You can cast the entire object so it always fits (not recommended - this might cause problems with other properties' types as they might stop working and auto completing for you)

<main style={{ "--nav-height": navHeight } as React.CSSProperties}>

CodePudding user response:

The error seems to indicate that you are using an invalid property for the style prop. Perhaps you are confusing --nav-height with height.

You can try the following:

<main style={{ height: "var(--nav-height)" }}></main>

CodePudding user response:

You're problem is not related to Typescript. You have this error because when you declare a style props, TS is waiting for valid properties like color, backgroundColor, etc... which your --nav-height is not.

To set the value of a CSS variable using JavaScript (and so, React, since it's just Javacsript), you use setProperty on documentElement's style property:

You have to do somehting like this :

    const createVariable = () => {
        document.documentElement.style.setProperty('--my-color', 'pink');
    }

    return (
        <React.Fragment>
            <h1 onClick={createVariable}>Click me to set the variable!</h1>
            <p style={{color: "var(--my-color)"}}>Look at me !</p>
        </React.Fragment>
    )
}
  • Related