What is JSX?
JSX (JavaScript XML) is a syntax extension that allows you to write HTML inside JavaScript. It makes React components more readable and expressive.
JSX Example:
const element = <h1>Hello, JSX!</h1>; Why Use JSX?
- Readable & Intuitive – Looks like HTML inside JavaScript.
- Prevents XSS Attacks – JSX escapes values automatically.
- Full JavaScript Power – You can use JavaScript inside JSX.
JSX Syntax Rules
1. Only One Parent Element
✅ Correct:
return ( <div> <h1>Hello</h1> <p>Welcome to React</p> </div> ); ❌ Incorrect:
return ( <h1>Hello</h1> <p>Welcome to React</p> ); Fix: Wrap elements inside a <div> or <> (fragment).
2. Use className Instead of class
✅ Correct:
return <h1 className="title">Hello, JSX!</h1>; ❌ Incorrect:
return <h1 class="title">Hello, JSX!</h1>; Why? class is a reserved keyword in JavaScript.
3. Expressions in JSX Must Be Inside {}
✅ Correct:
const name = "React"; return <h1>Welcome to {name}!</h1>; ❌ Incorrect:
const name = "React"; return <h1>Welcome to name!</h1>; 4. Self-Closing Tags for Elements Without Children
✅ Correct:
return <img src="logo.png" alt="React Logo" />; ❌ Incorrect:
return <img src="logo.png" alt="React Logo"></img>; Using JavaScript Inside JSX
Example: Dynamic Content in JSX
const age = 25; return <p>{age >= 18 ? "Adult" : "Minor"}</p>; Example: Calling Functions in JSX
function getGreeting(name) { return `Hello, ${name}!`; } return <h1>{getGreeting("React")}</h1>; JSX Without Babel (Pure React)
Under the hood, JSX compiles into React.createElement().
JSX:
const element = <h1>Hello, JSX!</h1>; Compiles to:
const element = React.createElement("h1", null, "Hello, JSX!"); JSX just makes writing React easier!
Summary
- JSX lets you write HTML inside JavaScript.
- Must have one parent element.
- Use
{}for JavaScript expressions. - Use
classNameinstead ofclass. - Self-close elements like
<img />.
Top comments (0)