What is JSX?

CodeyMaze
3 min readMar 18, 2022

--

JSX stands for JavaScript XML. It is a syntax extension to javascript. Take a look at this code :

const element = <h1>Hi, I am JSX</h1>

This is called JSX. JSX comes with the full power of javascript.

React uses React.createElement method to create HTML elements. JSX allows us to write HTML elements in JavaScript and place them in the DOM without using React.createElement. JSX produces react elements.

The corresponding syntax of the above JSX using React.createElement would be:

const element = React.createElement('h1', {}, 'Hi, I am JSX')

Let’s take another example :

const element = <h1><p>I am P inside H1 tag</p></h1>

The corresponding syntax using React.createElement would be:

const element = React.createElement('h1', {}, React.createElement('p', {}, 'I am P inside H1 tag'));

As you can see, writing code in this way will become complicated if we have to write multiple nested elements. JSX makes it easier to write and add HTML in React. After compilation, JSX expressions become regular JavaScript function calls and evaluate to JavaScript objects.

JSX also helps prevent XSS(Cross-site-scripting) attacks in the application. React DOM escapes any values embedded in JSX before rendering them. Everything is converted to a string before being rendered.

Expressions

We can evaluate JavaScript expressions in JSX by placing them in curly braces {}

const element = <p>Expression : {15+20} </p>

To print the variable value we can use the same {} curly braces notation.

const name = 'Preet'; const element = <p>Hi, My name is : {name} </p>

We can write JavaScript code inside JSX with the help of curly braces {}. Strings, numbers, and other primitive types can be easily printed with the help of {} notation but for objects, we need to use the key to print the value. For ex.

Printing the Person object in this way will give us an error:

In this way, we can print the values of the object.

Conditional Expressions

We can write conditions with the help of {} curly braces notation.

Adding Class

To add class attribute we have to use className instead of class. As we are writing code in JavaScript & class is a reserved keyword in JavaScript, so React decided to use className instead of writing class.

Subscribe to our Youtube channel for more videos :

https://www.youtube.com/channel/UCEXWe9R6-ppk4zhNo2JbtmQ

--

--

CodeyMaze

Crafting Solutions Through Code & Words https://codeymaze.com Feel free to follow me :)