Build your own Reactjs from scratch : Chapter 5 -Fixing JSX Dev Runtime and First version of the render function

Build your own Reactjs from scratch : Chapter 5 -Fixing JSX Dev Runtime and First version of the render function

if you start our example project in dev mode now it will give you an error

     [vite] Internal server error: Failed to resolve import "../jsx-run-time/jsx-dev-runtime" from "index.jsx". Does the file exist?

this is because we have not specified jsx-dev-runtime (https://esbuild.github.io/api/#jsx-dev) as our jsxRuntime in @vitejs/plugin-react is set to be automatic by default.

Either we have to specify jsxRuntime as classic or we have to create our own jsx-dev-runtime in the folder jsx-run-time and import jsxDEV from react/jsx-dev-runtime

To make the tutorial simple we will use the second approach and create our own jsx-dev-runtime

for now, we will use the same code for both jsx-runtime and jsx-dev-runtime

We will write createElement function in runtime and export as jsxDEV

const createElement = function (tag, { children, ...props } = {}) {
  const element = document.createElement(tag);
  if (props) {
    for (const prop in props) {
      element[prop] = props[prop];
    }
  }

  if (Array.isArray(children)) {
    children.forEach(child => {
      if (typeof child === 'string') {
        element.appendChild(document.createTextNode(child));
      } else if (child instanceof HTMLElement) {
        element.appendChild(child);
      }
    });
  } else if (typeof children === 'string') {
    element.appendChild(document.createTextNode(children));
  } else if (children instanceof HTMLElement) {
    element.appendChild(children);
  }

  return element;
};

Our createElement function will take tag, children and props as arguments and return the HTML element

Now we can start our project and it will work fine

but see the output in the browser

It simply renders the function as a string and not the html element

This is because our render function is not returning the element but the function itself so we have to make a slight change in our render function. the render function should receive a function itself and call the function and render the HTML

const createRoot = function (container) {
    return {
      render: function (creatEelement) {
        const html = creatEelement();
        container.appendChild(html);
      }
    };
  };

we have also made the changes in the unit test for the createRoot function

Now if we run our app you can see the output in the browser Finally we made our first version of the react app which render functional component using our own react library

We will add more Features to the createElement and render Function in the coming blog posts
All the codes can be found in the GitHub branch chapter-5 (https://github.com/nishammahsin/react-like-library/blob/chapter-5)