Skip to content Skip to sidebar Skip to footer

Manipulating Dom In React

I am aware that manipulating DOM directly in react is not a considered a good practice. As react reconciliation engine will hit performance when comparing virtual DOM and real DOM

Solution 1:

In that case, rather than setting innerHTML directly, you should be using dangerouslySetInnerHTML:

classComponentextendsReact.Component {
  state = {
    innerHTML: '',
  }

  handleChange() {
    this.setState({ innerHTML: '...' });
  }

  render() {
    return<divdangerouslySetInnerHTML={ { __html:this.state.innerHTML } }></div>;
  }
}

As stated in the docs:

dangerouslySetInnerHTML

dangerouslySetInnerHTML is React’s replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it’s dangerous.

Also, when using dangerouslySetInnerHTML, React will ignore that part of the DOM when diffing the virtual DOM and the real DOM (reconciliation), so it will be more performant as it has less work to do.

And in any case, if you do:

document.getElementById('test').innerHTML = this.state.innerHTML;

At some point in your code, maybe in componentDidUpdate(), and then render() is called again (when you update the state or a parent component re-renders), your changes will be overwritten, so you would need to be constantly updating it, which might produce a small but noticeable flash and reduce performance, as each render will have to update the DOM 2 times (one from React and the other one from innerHTML).

Solution 2:

you can look into using ReactRef instead of having to manipulate the DOM directly, it's easier, safer and more best practice.

check here

Post a Comment for "Manipulating Dom In React"