Wednesday, May 13, 2020




JSX is JavaScript XML. It is a syntax extension to JavaScript. It allows us to embed HTML mark up in React. It is not optional as we can write similar code with JavaScript, but JSX extremely handy tool to work with ReactJS. JSX makes has an extra layer of ease over JavaScript to work with React elements and components. 

We need to put lesser effort to work with JSX, however, they are eventually compiled into the JavaScript before running in a web browser. 

So, JSX provides syntactic sugar for the React.createElement(component, props, …children) function. 

For example, 

const element=<h2> Hello ReactJS!!!</h2>

The syntax is not normal, neither it is HTML nor string. It is an intermediate representation that is used to compose ReactJS components.

Embedding JavaScript expressions into the JSX

We can embed the JavaScript expression into JSX by wrapping them in curly { } brackets.

var name="ReactJS";
const element=<h2> Hello {name} !!!</h2>

Any valid JavaScript expression can be kept within the curly brackets.

function sum(a,b)
return a+b;
const element=<div><p> The sum is {sum(4,5)} </p></div>


JSX is also JavaScript expressions

JSX expressions are transformed into normal JavaScript function calls and evaluate to JavaScript objects after the compilation. It means we can put them within JavaScript statements such as if, and for statements. We can also assign them to variables. The JavaScript function can accept them as arguments and a function can also return a JSX expression.

Specify the children to JSX elements.

const name="ReactJS";
const description="It is a JavaScript library";
const element=<div><h2>Hello {name}</h2><h3>{description}</h3></div>;
The <div> tag has two children. 

JSX to JavaScript object transformation

The JSX is eventually transformed into JavaScript objects by the Babel, For example, the following JSX code,
const element = (
  <h2 className="message">
    Welcome to ReactJS
is transformed into

const element = React.createElement(
  {className: 'message'},
  'welcome to ReactJS'
by the compiler. The JSX is converted into the React.createElement() calls. A JSX expression is first tested for bugs and if everything is alright then it is compiled down to the JavaScript object.

<div class="simpleButton"><button>Hello world!</button></div>
is compiled down to,

React.createElement("div", {
    class: "simpleButton"
  }, React.createElement("button", null, "Hello world!"));

If you want to try out how some other specific JSX expressions are transformed into JavaScript, you can visit the online Babel compiler.