Home > database >  Why Am I unable to dynamically update my CSS values using variable in reactjs?
Why Am I unable to dynamically update my CSS values using variable in reactjs?

Time:06-07

So, I am trying to update the CSS values using CSS variables. It's my first time of trying to do this though. No error seen, the previous value remained, didn't change. Here are my codes:

CSS variable declaration

:root {
--tx: -0%;
}

.move{ 
 transform: translateX(var(--tx));
}

In my react, I created a useState and provided a -33 value to it for testing

 const [movePosition, setMovePosition] = useState(-33);

I created a function to handle to check if the CSS variable would be updated using the value provided in the movePosition state

const handleNextSlide = ()=>{
  setSlider1(slider1   1);
  setSlider2(slider2   1);
  setSlider3(slider3   1);
 getComputedStyle(document.documentElement).getPropertyValue('--tx', 
 `${movePosition}%`);
 }

I created a button to handle the onClick event that calls the function above

 <MdNavigateNext onClick={handleNextSlide}/>

When clicked, the CSS values does not change to the movePosition state value which is -33. I even hard coded it, it still didn't change. How can I make this work?

CodePudding user response:

The right API to update CSS variables is:

const handleNextSlide = ()=>{
  setSlider1(slider1   1);
  setSlider2(slider2   1);
  setSlider3(slider3   1);
  document.documentElement.style.setProperty('--tx', `${movePosition}%`);
}

Reference: https://css-tricks.com/updating-a-css-variable-with-javascript/

CodePudding user response:

In reactjs you you can update CSS variables by wrapping it in a string

<MdNavigateNext onClick={handleNextSlide} style={{'--tx':`${movePosition}%`}}/>
  • Related