Created
July 8, 2021 11:09
-
-
Save codemile/3c22f75d397538d87b19d4ecc86d4c22 to your computer and use it in GitHub Desktop.
Hook that reads/writes #CSS variables. Turns a CSS variable into a useState() hook for your web components and lets you change them at run-time.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const useCSSVariable = (name: string) => { | |
const [value, setState] = useState( | |
window.getComputedStyle(document.documentElement).getPropertyValue(name) | |
); | |
const setValue = useCallback( | |
(newValue: string) => { | |
setState(newValue); | |
document.documentElement.style.setProperty(name, newValue); | |
}, | |
[name] | |
); | |
return [value, setValue]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment