Skip to content

Instantly share code, notes, and snippets.

@finreinhard
Created June 30, 2021 17:39
Show Gist options
  • Save finreinhard/1c001809d0f17630a562c6ddd61d9047 to your computer and use it in GitHub Desktop.
Save finreinhard/1c001809d0f17630a562c6ddd61d9047 to your computer and use it in GitHub Desktop.
import { useEffect, useState } from 'react';
interface Variables {
[variable: string]: string;
}
const useCSSRootVariable = (variables: Variables): void => {
const [styleTag] = useState(() => document.createElement('style'));
useEffect(() => {
document.head.append(styleTag);
return () => {
styleTag.remove();
};
}, [styleTag]);
useEffect(() => {
styleTag.innerText = `:root {${Object.entries(variables).map(
([variable, value]) => `--${variable}: ${value};`
)}}`;
}, [styleTag, variables]);
};
export default useCSSRootVariable;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment