Build your own Reactjs from scratch - Chapter 4 Implementing JSX

In previous chapter we learned how to use babel to transform JSX to Plain Javascript

in this chapter, we will write the actual implementation transformer function jsx()

The component

const ui = () => <div id="root">Hello world</div>

is equivalent to following code after compilation


const ui = jsx('div', {id: 'root', children: 'Hello world'})

if we have more than one child we can use an array

const ui = () => <div id="root">
    <h1>Hello world</h1>
    <p>lorem ipsum</p>
</div>

is equivalent to following code after compilation

const ui = jsx('div', {id: 'root', children: [
    jsx('h1', {children: 'Hello world'}),
    jsx('p', {children: 'lorem ipsum'})
]})

Since we do not have actual implementation of jsx function , if we run npm run build we will see the build file as below

Here each child is an object with type and props, the type is the tag name and props is an object with all the attributes and children

so we can write our jsx function in the jsx run time like this

function jsx(type, props) {
    return {
        type,
        props
    }
}

if you run npm run build now in the build file we can see that we are using jsx function to transform jsx to plain javascript

you have to also export the jsxs function inorder to support multiple children the jsx run time

final version of jsx run time will look like this

export const jsx = (tag, props) => {
   return { tag, props };
  };

export const jsxs = jsx;

We will rewrite our render function in the next chapter.
See the full code here : https://github.com/nishammahsin/react-like-library
Happy Learning!