React JSX
JSX is a powerful syntax extension in React that makes writing and managing UI components easier and more readable.
JSX means JavaScript XML
It allows writing HTML inside JavaScript
It makes React code simple and readable
Without JSX we use createElement
With JSX we write HTML directly
javascript
const element = <h1>I Love JSX</h1> // with JSX
const element = React.createElement("h1", {}, "I do not use JSX") // without JSXJSX Expressions
We can use JavaScript inside curly braces
javascript
const element = <h1>{5 + 5}</h1>Multiple Lines HTML
Use parentheses for multiple lines
javascript
const element = (
<ul>
<li>Apple</li>
<li>Banana</li>
</ul>
)One Parent Element
JSX must have one parent element
Wrong
html
<h1>Hello</h1>
<p>Hi</p>Correct
html
<div>
<h1>Hello</h1>
<p>Hi</p>
</div>Fragment
We can use empty tag instead of div
html
<>
<h1>Hello</h1>
<p>Hi</p>
</>Close Tags
All tags must be closed
html
<input type="text" />className
Use className instead of class
html
<h1 className="title">Hello</h1>Comments in JSX
Use this format
html
{/* This is comment */}JSX in Components
Components return JSX
javascript
function Car() {
return <h1>My Car</h1>
}JSX with Variables
javascript
function Car() {
const brand = "Ford"
return <h1>{brand}</h1>
}React JSX If Statements
We cannot write if statement directly inside JSX
Option 1 Use if outside JSX
javascript
function Fruit() {
const x = 5
let result = "Apple"
if (x < 10) {
result = "Banana"
}
return <h1>{result}</h1>
}Option 2 Use ternary operator
javascript
function Fruit() {
const x = 5
return <h1>{x < 10 ? "Banana" : "Apple"}</h1>
}Always use curly braces for JavaScript inside JSX