React is a JavaScript library for building user interfaces. But why do we need it? Let's understand from first principles.
Task: Create multiple HTML elements with styles, className, id, and text content using JavaScript.
// Create first element
const h1 = document.createElement('h1');
h1.style.backgroundColor = 'orange';
h1.style.color = 'black';
h1.style.fontSize = '30px';
h1.id = 'first';
h1.className = 'ele1';
h1.textContent = 'Hello Coder Army';
document.getElementById('root').appendChild(h1);
// Create second element
const p = document.createElement('p');
p.style.color = 'blue';
p.id = 'para';
p.className = 'text';
p.textContent = 'This is a paragraph';
document.getElementById('root').appendChild(p);
// Create third element... (repetitive!)
Problems:
Let's create a simple library to make element creation easier:
const React = {
createElement: function(tag, attribute, children){
const element = document.createElement(tag);
for(const key in attribute){
if(key === 'style'){
Object.assign(element.style, attribute[key]);
}
else {
element[key] = attribute[key];
}
}
element.textContent = children;
return element;
}
};
const ReactDOM = {
render: function(element, root){
root.appendChild(element);
}
};
const element1 = React.createElement(
'h1',
{
style: {backgroundColor: "orange", color: "black", fontSize: "30px"},
id: "first",
className: "ele1"
},
"Hello Coder Army"
);
ReactDOM.render(element1, document.getElementById('root'));
Benefits: