Why can’t browsers read JSX ?
React is a JavaScript Library which is used to create web applications. React uses JSX that allows us to write JavaScript objects inside the HTML elements. JSX is neither a string nor HTML. It is a syntax extension of JavaScript. JSX makes code easy and understandable.
const num = 20 + 30; const ele = <h1>{num} is 50</h1>;
JSX is not a valid JavaScript as they are embedded in HTML elements. As JSX is combination of HTML and JavaScript it is not supported by Browsers. So, if any file contains JSX file, Babel transpiler converts the JSX into JavaScript objects which becomes a valid JavaScript. Thus, browsers understands the code and executes. Browsers can’t read JSX because there is no inherent implementation for the browser engines to read and understand them. JSX is not intended to be implemented by the engines or browsers, it is intended to be used by various transpilers to transform these JSX into valid JavaScript code.
Let’s see how browsers run JSX and how it converts into JavaScript. In order to run JSX create a react application.
Create react application:
Step 1: Create a react application using the following command.
npx create-react-app foldername
Step 2: Change your directory to the newly created folder by using the following command.
cd foldername
Project Structure: A project structure is created as shown below;
Project Structure
Step 3: Now, open index.js and add the following code. This code is written in JSX.
index.js
import React from 'react' ; import ReactDOM from 'react-dom' ; const ele = ( <div className = 'page' style = { { textAlign: 'center' } }> <h1 id = 'head' > Never Stop Learning!!! </h1> <h2 style = { { color: 'green' } }> Because life never stops teaching </h2> <p> From GeeksforGeeks </p> </div> ); ReactDOM.render(ele, document.getElementById( 'root' )); |
Explanation: The above code is converted into JavaScript as shown below using Babel compiler, because JSX is not supported by browsers it converts the JSX code into JavaScript.
Step 4: Below shown code is a converted code of JSX i.e. JavaScript code(Without JSX). Add the following code in index.js to see how it works.
index.js
import React from 'react' ; import ReactDOM from 'react-dom' ; const ele = React.createElement( "div" , { className: 'page' , style: { textAlign: 'center' } }, React.createElement( "h1" , { id: 'head' }, "Never Stop Learning!!!" ), React.createElement( "h2" , { style: { color: 'green' } }, "Because life never stops teaching" ), React.createElement( 'p' , null , "From GeeksforGeeks" ) ); ReactDOM.render(ele, document.getElementById( 'root' )); |
Step to run the application: Open the terminal and type the following command.
npm start
Output: Both the codes give the same output. Because they are the same codes written in JSX and another one is Converted JavaScript.
Please Login to comment...