What is the difference between createElement(tag)
and appendChild(node) and how does this relate
to React?
createElement(tag) vs appendChild(node)
Using Both to Create the DOM Tree:
We’ll build:
<form>
<label></label>
<ul>
<li></li>
<li></li>
</ul>
</form>
JavaScript Code:
const form = document.createElement('form');
const label = document.createElement('label');
const ul = document.createElement('ul');
const li1 = document.createElement('li');
const li2 = document.createElement('li');
// Build the structure
ul.appendChild(li1);
ul.appendChild(li2);
form.appendChild(label);
form.appendChild(ul);
// Attach to the page (e.g., body)
document.body.appendChild(form);
How Does This Relate to React?
In React, React.createElement() is a virtual version of this DOM API.
For example:
React.createElement('form', null,
React.createElement('label', null),
React.createElement('ul', null,
React.createElement('li', null),
React.createElement('li', null)
)
)
React uses this behind the scenes to build a Virtual DOM, which is then efficiently synced with the real DOM.
No comments:
Post a Comment