What is JSX?


 JSX is an extension to javascript. It is a template script where you will have the power of using HTML and Javascript together.
Here is a simple example of a JSX code.
const h1tag = "<h1>Hello, from Guru99 Tutorials!</h1>";
Why we need JSX in React?
For a UI, we need Html, and each element in the dom will have events to be handled, state changes, etc.
In case of React, it allows us to make use of Html and javascript in the same file and take care of the state changes in the dom in an efficient manner.
Expressions in JSX
Here is a simple example of how to use expressions in JSX.
In our earlier example we had written something like :
index.js
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<h1>Hello, from Viastudy Tutorials!</h1>,
    document.getElementById('root')
);
We will now change the above code to add expressions. Expressions are used inside curly brackets {}, and they are expanded during run time. Expressions in react are the same as javascript expressions.
index.js
import React from 'react';
import ReactDOM from 'react-dom';
const display = "Hello, from Guru99 Tutorials!";
const h1tag = "<h1>{display}</h1>";
ReactDOM.render(
    h1tag,
    document.getElementById('root')
); 
Let us now test the same in the browser.

You can see that the {display} expression is not replaced. React does not know what to do when an expression is used inside the .js file.

Let us now add changes and create a .jsx file, as shown below:

test.jsx

import React from 'react';
import ReactDOM from 'react-dom';

const display = "Hello, to Guru99 Tutorials";
const h1tag =<h1>{display}</h1>;
export default h1tag;
We have added the required code and will use the text.jsx file in index.js.We want the h1tag variable to be used inside script.js, so the same is exported as shown above in the test.jsx

Here is the modified code in index.js

import React from 'react';
import ReactDOM from 'react-dom';
import h1tag from './test.jsx';

ReactDOM.render(
    h1tag,
    document.getElementById('root')
);
To use the test.jsx in index.js we have to import it first as shown below:

import h1tag from './test.jsx';
We can use the h1tag now in the ReactDOM.render as shown below:

ReactDOM.render(
    h1tag,
    document.getElementById('root')
);
Here is the output when we check the same in the browser:


No comments:

Post a Comment