Fun with React Elements and JSX

Sourav Singh
3 min readJun 14, 2020

--

A small read on, why you should think less about JSX and more about what happens under the hood.

As the official doc says, JSX is just syntactical sugar.

Let’s take an example :

Can you render this App component and output something like this?

Did you spot the difference in JSX and the output? How can you make the h2 text render something different from what you wrote in JSX?
You can pause the read and try yourself first before looking into the solution.

We need to understand that the JSX we write, does not directly render onto the DOM. Welcome to React 🙅🏻‍♂️

JSX is actually converted to React elements with dependencies like babel-plugin-transform-react-jsx.

So technically, the render function returns React elements. React.createElement is the function that is used for this purpose.

✳️ React.createElement accepts the following arguments :

type : “h1”, “div”, “span” etc i.e It would be a string in case of the Host Components.

props : an object containing the props, that you pass to the elements such as key, className. e.g {key:5 ,className:”App”}

children : Thing which gets rendered inside the element. It can be a text (inside h2) or array of react elements (inside div)

There can be other arguments which we don’t need right now. We will take them up in …rest.

So, the given JSX is similar to writing this :

Through the React elements, Fiber nodes are created, and then comes the work lifecycle in which the rendering happens. The work lifecycle is out of scope for this article.

So, we know that the rendering process is very far right now. And we can use the intermediate steps to create our output. We are gonna modify the createElement of React to have a magical/unexpected behavior.

✳️ Return of React.createElement looks like this :

{
$$typeof: Symbol(react.element),
type: 'h2’,
props: {
key: "2",
className:"...."
children: "..normal text"
}

}

✳️ We will take the existing function of React.createElement and will do a small play.

This hardcodes the children of all h2 tags in your App. We just modified a react element.

Similarly, you can even change the type and render buttons in place of divs. Give it a try.

✳️ Another cool thing is that you can modify your fav React built sites like Instagram or Twitter using Chrome console with the attached debugger.

Here is the link to the working code so that you can play with it.
✳️ https://codesandbox.io/s/elastic-shtern-i6dvh?file=/src/App.js

Happy coding…! Stay Home, Stay Safe.

--

--

Sourav Singh
Sourav Singh

Written by Sourav Singh

Software Engineer @Amazon, Prime Video | Previously at Disney+Hotstar

No responses yet