Loading content...
Loading content...
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 JSXWe can use JavaScript inside curly braces
javascript
const element = <h1>{5 + 5}</h1>Use parentheses for multiple lines
javascript
const element = (
<ul>
<li>Apple</li>
<li>Banana</li>
</ul>
)JSX must have one parent element
Wrong
html
<h1>Hello</h1>
<p>Hi</p>Correct
html
<div>
<h1>Hello</h1>
<p>Hi</p>
</div>We can use empty tag instead of div
html
<>
<h1>Hello</h1>
<p>Hi</p>
</>All tags must be closed
html
<input type="text" />Use className instead of class
html
<h1 className="title">Hello</h1>Use this format
html
{/* This is comment */}Components return JSX
javascript
function Car() {
return <h1>My Car</h1>
}javascript
function Car() {
const brand = "Ford"
return <h1>{brand}</h1>
}We cannot write if statement directly inside JSX
javascript
function Fruit() {
const x = 5
let result = "Apple"
if (x < 10) {
result = "Banana"
}
return <h1>{result}</h1>
}javascript
function Fruit() {
const x = 5
return <h1>{x < 10 ? "Banana" : "Apple"}</h1>
}Always use curly braces for JavaScript inside JSX