DEV Community

Asad ur Rehman
Asad ur Rehman

Posted on

How Babel transforms JSX to React.createElement()

Consider the following component

const AnimalJSX = (props)=>{
    return (
        <div>
            <h1>{props.name}</h1>
            <p>{props.description}</p>
        </div>
    )
}
Enter fullscreen mode Exit fullscreen mode
<AnimalJSX name="Dog" description="A brief description"/>
Enter fullscreen mode Exit fullscreen mode

What is JSX ? It is a syntax extension to Javascript to describe what the UI shoudl look like.. JSX produces react elements which are renderd on browser. Babel is used to transform JSX to raw javascript.

Ever wondered how this works under the hood how babel transforms this to raw javascript methods of React.

React uses React.createElement() to create an elements that needs to be rendered. Here is a simplified version of the createElement function signature.

React.createElement(type,props,children)
Enter fullscreen mode Exit fullscreen mode

type: the type of element you want to create for example: h1,h2, div,span or another React.createElement() object.

props: the props we want to pass into the components for example className for styling or other parameters.

children: An array of text nodes or other React.createElement objects we want to render as children for this particular component.

If you pass a text value as an array object it will be treated as a text node only.

Consider the following code that renders the AnimalJSX component but using createElement method.

const Animal = (props)=>{
    return React.createElement("div",{},[
        React.createElement("h1",{key:1},props.name),
        React.createElement("p",{key:2},props.description)
    ])
}
Enter fullscreen mode Exit fullscreen mode

Now if we want to render the Animal component in vanilla react without using JSX here is how we'll do it

const container = document.getElementById("root");

const root = ReactDOM.createRoot(container);

root.render(React.createElement(Animal,{name:'Dog',description:'A type of dog'},null));
Enter fullscreen mode Exit fullscreen mode

We can either omit the children parameter or just for clarity I am passing null to it. This will render as following:

Image description

Top comments (0)