This content originally appeared on DEV Community and was authored by Geetika Bajpai
Root Div: The serves as a container where the custom-rendered content will be inserted.
Custom Render Function:
The customRender function takes two arguments:
- reactElement: An object representing the element to be rendered.
- container: The DOM element where the rendered element will be appended.
DOM Element Creation:
const domElement = document.createElement(reactElement.type); creates a new DOM element of the type specified in reactElement.type (in this case, an element).
Setting Inner HTML:
domElement.innerHTML = reactElement.children; sets the inner HTML of the newly created DOM element to the value of reactElement.children (which is the text "Click me to visit google").
Setting Attributes:
- domElement.setAttribute('href', reactElement.props.href); sets the href attribute of the element to the URL specified in reactElement.props.href ("http://google.com").
- domElement.setAttribute('target', reactElement.props.target); sets the target attribute of the element to the value specified in reactElement.props.target ("_blank").
Appending to Container:
container.appendChild(domElement); appends the newly created and configured DOM element to the specified container (mainContainer).
React Element Object:
The reactElement object simulates a simplified React element with a type (the type of HTML element), props (an object containing attributes for the element), and children (the inner content of the element).
Selecting Main Container:
const mainContainer = document.querySelector('#root'); selects the
element with the ID of "root" to serve as the container for the rendered content.Rendering the Element:
customRender(reactElement, mainContainer); calls the customRender function with the reactElement object and the mainContainer DOM element, rendering an anchor () element inside the root div.
Result
When this code runs, it creates an anchor () element with the text "Click me to visit google", which links to http://google.com and opens in a new tab (target="_blank"), and appends it to the div with the ID root in the HTML document.
Now we modulate above code by using loops
This content originally appeared on DEV Community and was authored by Geetika Bajpai
Geetika Bajpai | Sciencx (2024-06-20T21:10:56+00:00) Create your own react library. Retrieved from https://www.scien.cx/2024/06/20/create-your-own-react-library/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.