I would like to define or update a CSS variable in React. I have seen numerous examples of this using the Styled Components library. Is there a way to set a CSS variable in React without something like Styled Components?
An example would be to update the definition each time state changes
useEffect( () => {
// update css variable
// --my-css-var: width 75%
}, [state])
Looks like this can be accomplished with style.setProperty() Docs
In React this would require the use of ref Docs so we can apply this to a particular element.
const reference = useRef(null);
const [state, setState] = useState(100);
useEffect(() => {
reference.current.style.setProperty('--my-css-var', state);
}, [state]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With