Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define CSS Variable w/o Styled Components

Tags:

reactjs

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])
like image 595
Newb 4 You BB Avatar asked Aug 25 '26 01:08

Newb 4 You BB


1 Answers

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]);
like image 198
Newb 4 You BB Avatar answered Aug 27 '26 15:08

Newb 4 You BB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!