Lecture-4 Create your own react Library

Sabhya AgarwalSabhya Agarwal
2 min read
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Custom React App</title>
</head>
<body>
    <div id="root"></div>
    <script src="./react.js"></script>
</body>
</html>
function customRender(reactElement, container){
    /*
    const domElement = document.createElement(reactElement.type)
    domElement.innerHTML = reactElement.children
    domElement.setAttribute('href', reactElement.props.href)
    domElement.setAttribute('target', reactElement.props.target)

    container.appendChild(domElement)
    */

    const domElement = document.createElement(reactElement.type)
    domElement.innerHTML = reactElement.children
    for (const prop in reactElement.props) {
        if (prop === 'children') continue;
        domElement.setAttribute(prop, reactElement.props[prop])
    }
    container.appendChild(domElement)
}

const reactElement = {
    type: 'a',
    props: {
        href: 'https://google.com',
        target: '_blank'
    },
    children: 'Click me to visit google'
}

const mainContainer = document.querySelector('#root')

customRender(reactElement, mainContainer)

The app is a function that converts into a tree (object) behind the scenes, and then it goes for rendering. Babel injects everything.

  • Curly brace syntax is used to treat the content inside as a variable in JSX.

  • Expression in JSX should be the evaluated outcome, not the whole JavaScript code

//code-1 
const ReactElement = {
     type: 'a',
     props: {
         href: 'https://google.com',
         target: '_blank'
     },
     children: 'Click me to visit google'
}

//code-2
const anotherElement = (
    <a href="https://google.com" target='_blank'>Visit google</a>
)


//code-3
const anotherUser = "chai aur react"

const reactElement = React.createElement(
    'a',
    {href: 'https://google.com',target: '_blank' },
    'click me to visit google',
    anotherElement
)

code-1 does not render because it is custom-made, and .render does not understand the keywords. It follows specific rules to convert functions to an object tree, so we can't rename them or change their order.

Code-2's anotherElement is converted into an object tree before rendering.

Code-3 has the correct naming and order after converting from Code-2.

Reference Video

0
Subscribe to my newsletter

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

Written by

Sabhya Agarwal
Sabhya Agarwal