Introduction to React

React is a JavaScript library for building user interfaces. But why do we need it? Let's understand from first principles.


Problem Statement

Task: Create multiple HTML elements with styles, className, id, and text content using JavaScript.

Without any helper (Traditional way):

// 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:

  1. Repetitive code
  2. Hard to maintain
  3. Error-prone
  4. Not reusable

Solution 1: Create Our Own Helper Library

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);
    }
};

Usage:

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: