Skip to main content

Command Palette

Search for a command to run...

Demystifying JSX

Everything you need to know about JSX

Updated
โ€ข2 min readโ€ขView as Markdown
Demystifying JSX

JSX ! JSX ! JSX ! What is JSX? ๐Ÿค”

conf.png

Hello everyone. In this blog, we will learn everything about JSX. What is JSX? Why do we need JSX? Is JSX mandatory? All your questions will be answered by the end of this blog.

Pre-requisite

  1. Basics of HTML
  2. Basics of JavaScript

Introducing JSX

When you started learning React, the very first thing you might have encountered is this statement -

const element = <p> Hello, World! </p>

Now, if you JavaScript you might be scratching your head. What is this weird syntax? It looks like a JS syntax but how can we write HTML snippets inside JS? ๐Ÿค”๐Ÿค”

There it is. The so-called JavaScript XML aka JSX. JSX is a syntax extension to JavaScript. It allows us to write HTML in React.

Why JSX?

The sole purpose of using JSX in React is that it allows us to have logic and markup in the same component.

Is JSX necessary to work with React?

Direct answer - NO. JSX is not necessary to work with React. But most people find it helpful as a visual aid when working with UI inside the JavaScript code.

How does JSX make our life easy?

We know that React is a JavaScript Library. We write JavaScript in React to display the UI. Let's see how.

First, we will see how we can use React without using JSX. In order to create an element in React, you have to write code in the following way-

const element = React.createElement( "h1", { }, "I am not JSX" )
ReactDOM.render( element, document.getElementById("root")

Read more about React.createElement

Let's see how we can create an element in React using JSX

const element = <h1> I am JSX <h1>
ReactDOM.render(element, document.getElementById("root"))

Now you might have understood how JSX can make our life easy when we have long and complex code.

Wait! But React only understand JS. How is it converting JSX to JS?

Babel comes to the rescue. Under the hood, it's the Babel that converts this JSX to JavaScript.

You can try writing JSX and see how it is compiled to JS here

That's all folks. I hope most of the common queries that beginners have related to JSX are now clear. If you like this post, please like and share ๐Ÿ˜‡

shrek.jpg