To set or to use a CSS variable into a JS context you could use a dedicated util function.
The util function to set it :
export const jsAsCSS = (name: string, value: string) => {
document.documentElement.style.setProperty(name, value);
}
The usage of the setter :
const HelloWorld = () => {
const setCSSVariable = () => {
Utils.jsAsCSS("--my-color", "red");
};
return (
<div>
<button onClick={setCSSVariable}>Click me</button>
</div>
);
};
The util function to use it :
export const cssAsJS = (name: string) =>
getComputedStyle(document.documentElement).getPropertyValue(name);
The usage of the user :
const myColor = cssAsJS("--color-red");