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
-
imgTag
: object which specifies the property -
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)
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>
)
}
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)
Eh, I think you imagined the custom render function. I see zero code here.
i have provided the code brother is it correct
i am new to dev.to therefore srry for not providing the proper content