DEV Community

Akhil Dhiman
Akhil Dhiman

Posted on

Breaking down JSX

JSX might seem like some fancy term but it's nothing more than syntactic sugar for the React.createElement() API.

React.createElement takes three parameters, i.e., type, props and children.

React.createElement(type, props, children)
Enter fullscreen mode Exit fullscreen mode
<button color="red">Click!</button>
Enter fullscreen mode Exit fullscreen mode

So, this is our JSX- a button with a color property. The HTML element/Component is our type here, color is our prop, and the text "Click" is children of our component.

The compiled code would look like this.

React.createElement("button", { color: "red" }, "Click!")
Enter fullscreen mode Exit fullscreen mode

What actually happens under the hood ?

Babel, the transpiler is mainly responsible for allowing us to use JSX because we know that in order for the browser to understand, the code has to be converted into ES5, and that's what Babel is doing. Any ES6 thing like arrow function, class, let etc. will be handled by Babel.

const App = (props) => {
    return (
        <div>
            `Hello, my name is {props.name}`
        </div>
    )
}

ReactDOM.render(<App name="Sam" />, document.getElementById("root")) // suppose we have index.html and there's an element with an id of root in which we are rendering our application
Enter fullscreen mode Exit fullscreen mode

Babel compiles the above code in the "form" that only browser can understand.

var App = function App(props) {
    return React.createElement("div", {name: "Sam"}, "hello")
}

ReactDOM.render(React.createElement(App,
 {name: "Sam"}
 ), document.getElementById("root"))
Enter fullscreen mode Exit fullscreen mode

Thank You for reading this article!!!

Follow me on Twitter for more updates.

Top comments (2)

Collapse
 
taulantsulko profile image
Taulant Sulko

This is a very good explanation of JSX. Thanks for sharing your insights.

Collapse
 
akhildhiman profile image
Akhil Dhiman

Glad you liked it. Thanks!