Building React in Vanilla JS : 102 - Enhancing createElement

Yogesh KanwadeYogesh Kanwade
2 min read

Enhancements to createElement

Right now we can pass in only one child to our createElement. Let’s ramp it up to handle multiple children. Our createElement also doesn’t handle props other than events, let’s add a setAttribute method so we can add some color! Now we have:

const createElement = (type, props, ...children) => {
  const element = document.createElement(type);
  for (const [key, value] of Object.entries(props)) {
    if (key.startsWith("on") && typeof value === "function") {
      const event = key.slice(2).toLowerCase();
      element.addEventListener(event, value);
    } else {
      element.setAttribute(key, value);
    }
  }

  children.forEach((child) => {
    const node =
      typeof child === "string" ? document.createTextNode(child) : child;
    element.appendChild(node);
  });
  return element;
};
💡
We are using rest operator to gather and club possibly multiple children being passed as arguments into a single array.

Now we can return multiple elements from our App with some added color!

function App() {
  const button = createElement(
    "button",
    { onClick: () => incrementScore(), style: "background-color:red" },
    `Global var ${score}`
  );

  const heading = createElement("h1", {}, "Hello World!");

  return createElement("div", {}, heading, button);
}

Render Function

A simple render function

function render(component, container) {
  container.innerHTML = "";
  container.appendChild(component);
}
  • component: a DOM element created using createElement.

  • container: the root DOM node where the UI will be mounted (e.g., document.getElementById("app")).

  • innerHTML = "": clears any existing DOM content (simulating re-render).

  • appendChild(component): mounts the new component.

const root = document.getElementById("app");

function App() {
  ....
}

render(App(), root);

Code Sandbox

2
Subscribe to my newsletter

Read articles from Yogesh Kanwade directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Yogesh Kanwade
Yogesh Kanwade

I'm Yogesh Kanwade, a final year Computer Engineering student with a deep passion for software development. I am a continuous learner, with hardworking and goal-driven mindset and strong leadership capabilities. I am actively exploring the vast possibilities of Web Development along with AWS and DevOps, fascinated by their impact on scalable and efficient web solutions.