Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 510
Jak111 Avatar asked Jul 07 '19 07:07

Jak111


People also ask

How do I focus an element using useRef?

focus input element using ref in react class components useRef hook with an initial value, return a mutable ref to DOM elements useEffect hook in react equivalent to ComonentDidMount called once component is mounted. set focus to the input element in use effect function Added ref to input attribute.

Does useRef notify content changes?

Keep in mind that useRef doesn't notify you when its content changes. Mutating the . current record field doesn't cause a re-render. If you want to run some code when React attaches or detaches a ref to a DOM node, you may want to use a callback ref instead.

Can I use useRef instead of useState?

If you want to update data and cause a UI update, useState is your Hook. If you need some kind of data container throughout the component's lifecycle without causing render cycles on mutating your variable, then useRef is your solution.


1 Answers

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

like image 56
Tobias Tengler Avatar answered Oct 19 '22 02:10

Tobias Tengler