JSX in React

RMAG news

What is JSX?
JSX is a JavaScript Extension Syntax used in React to easily write HTML and JavaScript together.

const jsx = <h1>This is JSX</h1>

This is simple JSX code in React. But the browser does not understand this JSX because it’s not valid JavaScript code.
So to convert it to browser understandable JavaScript code, we use a tool like Babel which is a JavaScript compiler/transpiler.
or you can use create-react-app which internally uses Babel for the JSX to JavaScript conversion.

To add JavaScript code inside JSX, we need to write it in curly brackets like this:

const App = () => {
const number = 10;
return (
<div>
<p>Number: {number}</p>
</div>
);
};

Inside the curly brackets we can only write an expression that evaluates to some value.

Following are the valid things you can have in a JSX Expression:

A string like “hello”
A number like 10
An array like [1, 2, 4, 5]
An object property that will evaluate to some value
A function call that returns some value which may be JSX
A map method that always returns a new array
JSX itself

Following are the invalid things and cannot be used in a JSX Expression:

A for loop or while loop or any other loop

A variable declaration

A function declaration

An if condition

An object

In the case of an object, it’s not clear how the object should be displayed. For example, should it be comma-separated key-value pairs or should it be displayed as JSON? So you will get an error if you try to display the object in a JSX expression. But we can use object properties instead.

Also note that undefined, null, and boolean are not displayed on the UI when used inside JSX.

So if you have a boolean value and you want to display it on the UI you need to wrap it in ES6 template literal syntax like this:

const App = () => {
const isAdmin = true;
return (
<div>
<p>isAdmin is {`${isAdmin}`} </p>
</div>
);
};

Leave a Reply

Your email address will not be published. Required fields are marked *