Hackernoon logoHow To Manipulate DOM Elements In React by@RAHULISM

How To Manipulate DOM Elements In React

Rahul Hacker Noon profile picture

@RAHULISMRahul

Developer and Blogger

DOM Manipulation is the process by which one can dynamically change the content of the web page. Working with DOM should be fairly easy and quick as it is always tree-structured, traversing the DOM is easy.

In React, changes are made to the 

Virtual DOM
 and then synced to the React DOM. This process is call Reconciliation. React can figure out which objects have been changed, and this process is called drifting.

Process of DOM manipulation

  • React will update the Virtual DOM
  • The previous state virtual DOM will then be compared with the updated Virtual DOM, to identify what has been changed in the objects. This is done using the Diffing Algorithm.
  • The changed objects will get updated on the Real DOM.

Example of Diffing Algorithm

  • When the root element is different
  • // Old version
    <div><Tree/></div>
    
    // New update
    <span><Tree/></span>

React will delete the tree, and rebuild the entire tree again.

  • When the Attribute is changed in the element
  • // Old
    <span id="span1" />
    
    //New
    <span id="span2" />

Only the difference will be found in the attribute and will be changed accordingly.

  • New child element added at the end
    • // old
      <ul>
          <li>Child1</li>
          <li>Child2</li>
      </ul>
      
      //New
      <ul>
          <li>Child1</li>
          <li>Child2</li>
          <li>Child3</li>
      </ul>

The new element will be added to the end of the list.

  • New element added at the beginning of the list
  • // Old 
    <ul>
        <li>Child1</li>
        <li>Child2</li>
    </ul>
    
    //New
    <ul>
        <li>Child3</li>
        <li>Child1</li>
        <li>Child2</li>
    </ul>

As the new element is added to the beginning it will be rebuilding the entire list again.

☕Thanks For Reading | Happy Coding🤨

I have written over 130+ Article on https://rahulism.tech

Previously published at https://rahulism.tech/article/dom-manipulation-in-react/

Tags

Join Hacker Noon

Create your free account to unlock your custom reading experience.