Mike Alejandro
Mike Alejandro

Reputation: 483

How bad is it to change the DOM in react?

I'm a noob react developer, and I'm currently building a MERN App.

My question to the community is, in my project I had to modify the DOM multiple times as shown below:

document.getElementsByTagName('body')[0].style = 'overflow: hidden';

I know that changing the DOM very often is not recommended in React.Js. So is it ok if I did it only to cut the body's scroll-bar?

Upvotes: 0

Views: 3334

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371049

In React, changing the DOM directly is usually bad because the state of the page should come directly from the state in React.

But React will render inside the body - the body can't be something returned by the JSX inside a React component, so doing

document.body.style = // ..

really is the only way to change the body's style.

The time you wouldn't want to do such a thing would be if the element being changed was being rendered by React, eg:

// some functional component
const clickHandler = () => {
  document.querySelector('.foo').style.backgroundColor = 'green';
};
return (
  <div className="foo" onClick={clickHandler}>foo</div>
);

because you could instead toggle some state inside the component which changes the returned JSX to include the different style.

That said, your approach of

document.getElementsByTagName('body')[0].style = 'overflow: hidden';

should be reconsidered, if possible:

  • Use document.body instead of getElementsByTagName
  • Do you really have to set the style of the whole <body>? It would be more inline with React to set the style of an element React is rendering, if possible - and then you can use the method mentioned above, of using state and the returned JSX instead of using DOM methods.

Upvotes: 3

Related Questions