React JSX
⚛️ React JSX
JSX (JavaScript XML) is a syntax extension used in React that allows you to write HTML-like code inside JavaScript.
It makes React components easier to write and understand.
Example:
🧠 Why JSX?
Without JSX, React code looks like this:
With JSX:
✔ Cleaner
✔ Readable
✔ Faster development
🔹 JSX Must Return a Single Parent Element
❌ Invalid:
✔ Valid:
Or use React Fragment:
🔹 Embedding JavaScript in JSX
Use { } to insert variables or expressions.
Expressions allowed:
🔹 JSX Attributes
Use camelCase for attributes.
| HTML | JSX |
|---|---|
class |
className |
onclick |
onClick |
tabindex |
tabIndex |
Example:
🔹 JSX with Conditional Rendering
Using ternary operator:
🔹 JSX with Lists
🔹 Self-Closing Tags
JSX requires proper closing:
✔ Valid:
❌ Invalid:
🎀 JSX in a Component
🧠 Summary
| Feature | JSX Benefit |
|---|---|
| HTML-like syntax | Easy to understand |
| Embeds JavaScript logic | Dynamic UI |
| Requires one parent element | Organized structure |
| Supports expressions | Flexible rendering |
Cleaner than React.createElement() |
Developer friendly |
