Search code examples
javascriptcssreactjsjsxref

React - How to apply styles via ref


I have a reference for a container and I want to change his background-position. That needs to happen inside of a function and the values are dynamic, so I can't create a class for that.

slideRef.current.style["background-position-x"] = "-262.5px"
setTimeout(function(){
  slideRef.current.classList.add("spin_animation");
  slideRef.current.style = {backgroundPositionX: "-" + scrollAmount + "px"}
 10);

I tried two ways, accessing a property and not using a camel case and the other one was passing the style as an object like an inline style.

How can I apply the background-position, accessing directly the ref?


Solution

  • elementRef.current.style.backgroundPositionX = "-262.5px";
    

    const App = () => {
      const elementRef = React.useRef(null);
      const handler = () => {
        if (elementRef.current) {
          elementRef.current.style.color = "red";
          elementRef.current.style.backgroundPositionX = "-262.5px";
          console.log(elementRef.current.style);
        }
      };
      return (
        <div className="App">
          <h1 ref={elementRef}>Sample Text</h1>
          <h2 onClick={handler}>Click me to change the style of the text</h2>
        </div>
      );
    }
    ReactDOM.render(<App />, document.getElementById("root"));
    <div id="root"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>