React JSX
JSX (JavaScript XML) is a templating method that allows us to write HTML in React. In other words, JSX is an HTML-like syntax used by React that extends ECMAScript so that HTML-like syntax can co-exist with Javascipt/React.
Using JSX
JSX looks like the simple HTML. We already used it in the previous tutorial. Let's have a look at the code from the previous tutorial:
import React from 'react'
import './App.css';
function App() {
return (
<div className="App">
<h1>Welcome to First React App</h1>
</div>
);
}
export default App;
Nested Elements
In order to return multiple elements, all of them need to wrapped within a container. We can use <div>
as a wrapper in such cases.
Here's an example:
import React from 'react'
import './App.css';
function App() {
return (
<div className="App">
<h1>Welcome to First React App</h1>
<p>First Paragraph Line</p>
<p>Second Paragraph Line</p>
</div>
);
}
export default App;
Expressions in JSX
In JSX, all expressions go inside the { } curly brackets. Expression can be any JavaScript expression, variable or a property. JSX will execute the expression within the curly brackets and return the result. Here's an example:
import React from 'react'
import './App.css';
function App() {
return (
<div className="App">
<p>{1 + 1}</p>
</div>
);
}
export default App;
The above example will display 2.
We cannot use if else statements inside the JSX. However, we can use the ternary operator for these type of operations. Let's check an example:
import React from 'react'
import './App.css';
function App() {
let x = 4;
return (
<div className="App">
<p>{x == 4 ? 'True': 'False'}</p>
</div>
);
}
export default App;
In the above example, the value of x is compared with 4. If it is equal, True will be displayed. If not, False will appear.