DEV Community

Cover image for Manual DOM Rendering with JavaScript vs. React's Virtual DOM
AnuraG Singh
AnuraG Singh

Posted on

Manual DOM Rendering with JavaScript vs. React's Virtual DOM

Introduction

This documentation explains how to manually create and render DOM elements using plain JavaScript. We will cover the implementation of a custom rendering function and its comparison to how JSX is processed in React.

creating a custom render function
we created a customRender function which takes two parameters

  1. imgTag : object which specifies the property
  2. root : parent element where the element is to be appended

Inside function definition we created img tag and added attributes to it
and in the end we appended it in the root div

  • overall we made the manually created the DOM and rendered it on the web page

manual insertion

let imgtag = {
    type:'img',
    props:{
        src:'https://www.google.com/images/branding/googlelogo/1x/googlelogo_light_color_272x92dp.png',
        alt:'image of google'
    }
}
function IMGrender(imgtag,root){
    let div = document.createElement(imgtag.type)
    for (const key in imgtag.props) {
        if(key === "children") continue;
        div.setAttribute(key,imgtag.props[key])
    }

    root.appendChild(div)
}

IMGrender(imgtag,root)
Enter fullscreen mode Exit fullscreen mode

Comparison to React

The customRender function manually performs tasks that React handles automatically when processing JSX. React uses a virtual DOM to efficiently manage and update the actual DOM.

  • here in react we can use JSX to make a component (html tags) which later get converted into the object like a object in a customRender function

Vite uses esbuild as its bundler to parse JSX code into JavaScript objects (AST - Abstract Syntax Tree).

using react

import React from 'react'
import ReactDOM from 'react-dom/client'
function Img(){
  return(
    <img src='https://www.google.com/images/branding/googlelogo/1x/googlelogo_light_color_272x92dp.png' alt='img'></img>
  )
}


Enter fullscreen mode Exit fullscreen mode

Summary

The custom render function demonstrates manual DOM manipulation, where you directly create and update elements. In contrast, React abstracts these details away using JSX and the virtual DOM, which allows for more efficient updates and simpler, more declarative UI code.

Top comments (2)

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

Eh, I think you imagined the custom render function. I see zero code here.

Collapse
 
anurag_singh_2jz profile image
AnuraG Singh

i have provided the code brother is it correct
i am new to dev.to therefore srry for not providing the proper content