How To Manipulate DOM Elements In React

Written by rahull | Published 2021/04/01
Tech Story Tags: react | webdevelopment | coding | javascript | front-end-development | frontend | beginners | learning | web-monetization

TLDR 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. React can figure out which objects have been changed, and this process is called drifting. The changed objects will get updated on the Real DOM. The new element will be added to the end of the list, and the entire tree will be rebuilt again as the new element is added.via the TL;DR App

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

Written by rahull | 18, Hustler. Code/Design.
Published by HackerNoon on 2021/04/01