Polyfill for ReactDOM.render

divyanshgothwal

Divyansh Gothwal

Posted on June 10, 2023

Polyfill for ReactDOM.render

In this article we are going to build a polyfill for ReacDOM.render() before react18 or ReactDOM.createRoot(${domElement}).render(${reactElement})

To do this we need to understand how reactElement is represent by react.

we have 3 cases

// case 1
let jsx1 = <div>Test</div>;
let reactElemen1 = { type: "div", props: { children: "Test" } };

// case 2
let jsx2 = (
  <div>
    <h1>Test</h1>
  </div>
);
let reactElemen2 = {
  type: "div",
  props: { children: { type: "h1", props: { children: "Test" } } }
};

// case 3
let jsx3 = (
  <div>
    <h1>TestH1</h1>
    <h2>TestH2</h2>
  </div>
);
let reactElemen3 = {
  type: "div",
  props: {
    children: [
      { type: "h1", props: { children: "TestH1" } },
      { type: "h2", props: { children: "TestH2" } }
    ]
  }
};
Enter fullscreen mode Exit fullscreen mode

Now we understand how a react element can look like.
Lets start coding a function which takes reactElement and domNode, then renders all the react element as child of domNode.
Below the recursive code for this.

// function for setting styles for an elemement
function setStyle(domNode, styles) {
  Object.keys(styles ?? {}).forEach((styleKey: any) => {
    domNode.style[styleKey] = styles[styleKey];
  });
}

// main function for rendering reactElement to domNode
export function render(reactElement, domNode) {
  const {
    type,
    props: { children, style }
  } = reactElement;
  // first create a domElement from using type.
  let createdElement = document.createElement(type);
  //setting styles
  setStyle(createdElement, style);
  // checking if children is array
  if (Array.isArray(children)) {
    children.forEach((child) => {
      createdElement = render(child, createdElement);
    });
  // if children is object type
  } else if (typeof children === "object") {
    createdElement = render(children, createdElement);
  } else {
    // if children is of type string
    createdElement.innerHTML = children;
  }
  // append createdElement to domNode. 
  domNode.appendChild(createdElement);
  return domNode;
}
Enter fullscreen mode Exit fullscreen mode

Here is the codesandbox for this.
custom renderer

There you go you have created your basic custom renderer which renders reactElement to domNode.

Obviously we have not handled Component types but that i will covering in next article.

πŸ’– πŸ’ͺ πŸ™… 🚩
divyanshgothwal
Divyansh Gothwal

Posted on June 10, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related