Home > front end >  assigning ref, className, and style arguments to React Component
assigning ref, className, and style arguments to React Component

Time:07-28

First of all, does the useRef have higher priority over className and style?

For example:

function Comp() {
  const comp_ref = useRef();

  useEffect(() => {
    if (comp_ref.current) {
      comp_ref.current.className = "local-container";
      comp_ref.current.style.color = "white";
    }
  }, [])

  return <div ref={comp_ref} className="global-container" style={{color: "black"}} ></div>
}

During the initial render, the returned div will have class of "global-container" and style color: black;.

However, after the initial render, the returned div will always have class of "local-container" and style color: white;.

First of all, is the above understanding correct?

CodePudding user response:

useRef does not have higher priority over className and style.

There are no priorities here. They are different things.

In your example you change the DOM directly after the render. This is why it changes the className and style. It depends which one will occur first.

However, after the initial render, the returned div will always have class of "local-container" and style color: white;

This is true only if you do not change again the className or style while rendering. Like using a state:

className={counter < 5 ? "global-container": 'new-class'}

If initially the counter is less than a 5. First it will be "global-container". Then after your useEffect it will be "local-container". And then when you increment the counter it will become 'new-class'.

  • Related