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:

const element = <h1>Hello React!</h1>;

✔ 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:

<h2>The sum is {5 + 5}</h2>

🔹 JSX Attributes

Use camelCase for attributes.

HTML JSX
class className
onclick onClick
tabindex tabIndex

Example:

<h1 className="title" onClick={handleClick}>
Click Me
</h1>

🔹 JSX with Conditional Rendering

Using ternary operator:

const isLoggedIn = true;

return <p>{isLoggedIn ? “Welcome!” : “Please login”}</p>;


🔹 JSX with Lists

const items = ["Apple", "Banana", "Mango"];

return (
<ul>
{items.map((item, index) => <li key={index}>{item}</li>)}
</ul>
);


🔹 Self-Closing Tags

JSX requires proper closing:

✔ Valid:

<input />
<br />

❌ Invalid:

<input>

🎀 JSX in a Component

function App() {
return <h1>Hello from JSX!</h1>;
}
export default App;

🧠 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

You may also like...