Why do we need JSX in React JS? | Beginners Guide

What is JSX in React js?

JSX is the word you are going to see and hear a lot in the world of react. So, it really important that you understand what is jsx and why is used in react js. The react library it’s an extension to write XML-like code for elements and components. And just like XML, JSX tags have tag names, attributes, and children.

Why do we need JSX?

JSX is not a necessity to write react application. You can definitely use React without JSX but JSX makes your React code simpler and more elegant. As we might have already seen, it provides a syntax which familiar to many developers. JSX ultimately translates to pure JavaScript which is understood by the browser.

Now, I am going to create React component using JSX and without using JSX. That way you not only understand how JSX translates to regular Javascript but also appreciate how it brings out simplicity in your code.

Create Component Using JSX

const Hello = () =>{
return(
<div>
<h1>Component with JSX</h1>
</div>
)}

Here, we have created the function component that returns what appears to be HTML but is in fact JSX. The functional component returns some content inside the <h1> tag. So, this is the JSX version of the Hello component. Now let’s rewrite the component without using JSX.

Output:

what is jsx in react js

Create Component  Without Using JSX

import React from 'react';

const Hello = () =>{
return React.createElement('div', nul, 'Component without JSX')
}

To help us do that the react library provides a create element method. So within the function the code now changes to return “React.createElement()“. This method minimum accepts three parameters. The first parameter is a string that specifies the HTML tag to be rendered, here we rendered ‘div‘ tag. The second parameter we get to pass any optional properties, here we don’t need any additional properties, so we can pass in null value. The third parameter is the childer of the HTML element, which means the children for ‘div’ tag. For our example, we simply have the text “Component without JSX” which we pass as the third parameter.

READ ALSO  Is it Useful to Create Functional Components in React JS?

See the output, our content is displayed inside the div element.¬† If you want to display in <h1> element, Instead of passing text in the third parameter we need to create another “React.createElement()” function. Then pass parameter the give below code:

const First = () =>{
  return(
    React.createElement('div', null, React.createElement('h1', null,'Component without JSX'))   
 )
  };

Output:

what is jsx in react js

See the output above, we can see that the text is successfully displayed inside the <h1> inside the <div> tag.

Leave a Reply