Create your own React Elements in Vanilla JS

React is a popular JavaScript library used to create Single Page Applications(SPA). While react does many things under the hood to a SPA, you can also make a react functionality yourself in plain JavaScript.

React injects all the html code into a single element called 'root'. Therefore, we will also create 'root' div on index.html

<div id="root"></div>

Now we will link our script file to the html file

<script src="./react.js"></script>

Let's start working on the react.js script file.

First step would be to take a reference of root div from our html page so that we can inject our elements into it.

// Getting the reference of root div from index.html file
const mainDiv = document.getElementById('root');

Now that we have the reference of our main Div, let's see what our element would be. Here I am taking 'a' tag as an example element I want to insert. You can take any other tag.

// Creating element for rendering
const reactElement = {
  type: 'a',
  props: {
    href: 'https://google.com',
    target: '_blank',
  },
  children: 'Click to visit Google',
};

In the code block above, we have taken a simple object which has properties such as element type, properties (props) and child node (children).

As we know what we want to create, we will need a custom function to create the element for us on DOM.

// Creating function to render our element
function customRender(reactElement, container) {
  const DOMElement = document.createElement(reactElement.type);

  for (const prop in reactElement.props) {
    DOMElement.setAttribute(prop, reactElement.props[prop]);
  }

  DOMElement.appendChild(document.createTextNode(reactElement.children));

  container.appendChild(DOMElement);
}

In the above code block, we have:
1. Created a function that takes 2 arguments, reactElement and container. You can name them anything you like. reactElement is the object we created before and container is the element in which we want to place our new element.
2. DOMElement variable holds the reference of new element we created on DOM using createElement function.
3. As there are multiple properties of in our object, we are loopinh through all the props and setting them on our new element.
4. Thereafter, we are adding text for visibility and readability for our users, on our newly created anchor tag.
5. FInally, we are adding the new element to the main container on DOM.

We have a function that we create a reactElement for us on DOM, now we just need to call it.

// Rendering method
customRender(reactElement, mainDiv);

The code above takes our reachElement object and mainDiv container and creates the element mentioned in reactElement inside our mainDiv.

This is basically how react elements are created.