What is JSX?
Subject: React
What is JSX?
JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like code inside JavaScript. Itβs used in React to describe what the UI should look like.
Although browsers donβt understand JSX directly, tools like Babel compile it into regular JavaScript.
β Example:
This gets compiled to:
β‘οΈ Check JSX Cheat Sheet (React Syntax)
π Why Use JSX?
- Declarative: Write UI in a way thatβs easy to read and understand.
- Compositional: Can nest and reuse components easily.
- Integrated: Combines HTML + JavaScript logic seamlessly.
β‘οΈ Check JSX Cheat Sheet (React Syntax)
π§± JSX Syntax Basics
1. Single Root Element Required
A JSX expression must have one parent element.
β Invalid:
β Valid:
2. Use className
Instead of class
3. Use camelCase for HTML Attributes
4. Expressions inside {}
Can include:
- Variables
- Function calls
- Operators
- Ternary expressions
5. Self-Closing Tags
6. Style in JSX
β‘οΈ Check JSX Cheat Sheet (React Syntax)
π§ JSX Advanced Concepts
1. Conditional Rendering
πΉ Ternary:
πΉ Logical &&
:
2. Lists & Keys
3. Fragments
4. JSX Inside Functions & Variables
β‘οΈ Check JSX Cheat Sheet (React Syntax)
β οΈ Common JSX Errors
Error | Fix |
---|---|
Missing parent element | Wrap with a <div> or <> |
class instead of className | Always use className |
Inline style syntax | Use camelCase and JS object |
Forgot to close tag | Use /> for self-closing tags |
β‘οΈ Check JSX Cheat Sheet (React Syntax)
π JSX Summary
Feature | Example |
---|---|
HTML + JS Mix | <h1>Hello, {name}</h1> |
Styling | style={{ color: 'red' }} |
Conditionals | {isLoggedIn ? <Welcome /> : <Login />} |
Lists | {items.map(item => <li>{item}</li>)} |
One Root Element | Always wrap elements in a single parent |
β‘οΈ Check JSX Cheat Sheet (React Syntax)
π Final Thoughts
JSX is not required, but it's highly recommended in React β it makes your code:
- Easier to write
- Easier to debug
- Closer to how HTML works
Advertisement Slot 1
Advertisement Slot 2