Using refs to modify an element in React.js

Viewed 609

Is it wrong to use refs to modify an element's properties? If so, why? Example:

myRef.current.innerHTML = "Some content";
2 Answers

That's wrong if it's possible to modify the component's JSX to implement the change instead. Whenever possible, one should be able to determine the JSX that gets rendered solely from the current state of the component; direct DOM mutation side-effects like .innerHTML should only be done when there's no other possible option.

For this case, put the content into a state variable instead, like:

const [spanContents, setSpanContents] = useState('foobar');

const changeSpanContents = () => {
  setSpanContents('Some content');
};

return (
  <div>
    <button onClick={changeSpanContents}>click</button>
    <span>{spanContents}</span>
  </div>
);

In some unusual cases, there exists no JSX syntax for the DOM mutation you want - for example, for putting a resize listener on the window. In such a case, you will have to resort to using vanilla DOM methods instead of doing it solely through React. The following pattern is common for such a case:

useEffect(() => {
  const handler = () => {
    // resize detected
  };
  window.addEventListener('resize', handler);
  return () => {
    window.removeEventListener('resize', handler);
  };
}, []);

I wouldn't say wrong but it depends on what you are going to do after changing the html. As React will loose control over that element, you would have a hard time if you need to work on that DOM. Also, it is risky because React have controls over DOM, when you change it manually, it could lead to unexpected behaviors.

Related