What is JSX in React | What is the use of JSX

What is JSX

what is jsx in react

In previous lesson, we have learnt how to create UI element in react. There are two ways to create element. 
  • Using createElement( ) method
  • Using JSX

JSX stand for Javascript JSX. In most cases, it look likes html. it makes it easier to create multiple elements. 

Lets create one heading element and one paragraph and wrap them in div container using both ways

By react method

var heading = React.createElement(
  'This is my heading'
var paragraph = React.createElement(
  'This is my first paragraph'
var element = React.createElement(

var root = document.getElementById('root');


var element = <div>
  <h1>This is my heading</h1>
  <p>This is my first paragraph</p>

var root = document.getElementById('root');


You can see that how simple it is to create nested elements using JSX. In background, Babel translate JSX code to react code. 
Visit babeljs.io, write JSX code to create element, you will see its live translation into react.

babel preset react

In our next lessons, we will code in JSX. You can load both in browser and see rendered html in Developer Tool, html of both will be same.

Javascript in JSX

You can write javascript variable, functions, expression, property or other expression in JSX inside curly brackets { } as below

var num1 = 5;
var num2 = 8;
var element = <h1>Sum of {num1} and {num2} is {num1 + num2}</h1>;

JSX Attributes

You can also write JSX attributes like html tag. You can specify string in quotes in the attributes as below

var container = <div tabIndex='0'></div>;

Javascript can be embedded in attributes in curly braces without putting quotes around curly braces as below

var container = <img src={person.homeURL} />;

It is not allowed to write both string in quotes and javascript in curly braces in one attributes.

JSX Advantages

  • It is easier to create component
  • JSX component can be re-used
  • Its syntax is like html
  • It is easily to understand
  • You have to write less code
  • It is SEO friendly
  • It comes with very helpful toolkit created by developers
  • Used to create interface in mobile app development

No comments:

Post a Comment