How to use useRef to change the style of a element?

25,460

You're trying to modify a non-existent backgroundColor property directly on your DOM element:

box.current.backgroundColor = "blue";

Which would (if it worked) modify your DOM element to this:

<div backgroundColor="blue" ... />

In order to make it work you need to modify the backgroundColor through the style property:

box.current.style.backgroundColor = "blue";

Working version of your snippet

Share:
25,460
Jak111
Author by

Jak111

Updated on July 08, 2020

Comments

  • Jak111
    Jak111 almost 4 years

    I want to use the useRef hook to change the style of a DOM element:

    const Box = props => {
      const box = useRef(0);
    
      const onClick = () => {
        box.current.backgroundColor = "blue";
      };
    
      return (
        <div>
          <div
            ref={box}
            style={{ width: "300px", height: "300px", backgroundColor: "red" }}
          />
          <button onClick={onClick}>Change color of box</button>
        </div>
      );
    };
    

    However, if I click on the button the backgroundColor of the box doesn't change.

    I also created a simple code snippet, which illustrates my problem.

  • Hamidreza Sadegh
    Hamidreza Sadegh almost 5 years
    don't forgot for sizable styles use "px" or percent
  • Anthony Cregan
    Anthony Cregan about 3 years
    I had the correct implementation for my usecase but forgot the 'px', thanks Hamidreza Sadegh!