3

I'm new to React.js and want to set some CSS variables in an inline style attribute on a rendered component based on some calculations in JS.

When using TypeScript, it seems that I have to declare a type for each CSS-variable. What I got so far does work:

interface VariableACSSProp extends CSSProperties {
  '--variable-a': string;
}
interface VariableBCSSProp extends CSSProperties {
  '--variable-b': string;
}

// …in component:
let variableAContent = …
let variableBContent = …

return (
  <div style={{ "--variable-a": variableAContent } as VariableACSSProp}></div>
  <div style={{ "--variable-b": variableBContent } as VariableBCSSProp}></div>
)

Question: Is there any other, simpler way to use CSS-variables? Because I have more of them to set and it seems much to complicated to have to declare an interface for each CSS variable if there are many of them (especially as the type is – from my point of view – irrelevant, since it not used in JS, but in CSS).

Preferably I would like to use something like

<div style=`--variable-b: ${variableBContent};`></div>

…but that seems to be invalid TypeScript, resulting in an error ({ expected).

1 Answer 1

3

You could extend Reacts' CSSProperties type with a generic string: string type:

import React, { CSSProperties, useCallback } from 'react';

type CSSVariables = CSSProperties & {
    [key: `--${string}`]: string | number;
};

And then use it like your example:

const variableBContent = '#FF0000';
<div style={{ '--variable-b': variableBContent } as CSSVariables}></div>

Stackblitz Demo

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

1 Comment

Probably extending CSSProperties would be easier, I don't see possible downsides

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.