Introduction to JSX
JSX (JavaScript XML) is a core concept in React that allows you to write HTML-like syntax inside JavaScript. It combines markup and logic in a single place, making your UI dynamic, readable, and maintainable.
1. JSX Syntax Basics
JSX looks like HTML but follows slightly different rules:
Single Parent Element: JSX must return a single root element.
// Correct
const element = (
<div>
<h1>Hello</h1>
<p>Welcome to React!</p>
</div>
);
// Incorrect
const element = <h1>Hello</h1><p>Welcome</p>;
Self-Closing Tags: All tags must be closed.
<img src="logo.png" alt="Logo" />
Attributes: Some HTML attributes have different names:
<div className="container">Content</div>
<label htmlFor="input">Name</label>
Event Handlers: Use camelCase instead of lowercase.
<button onClick={() => alert("Clicked!")}>Click Me</button>
2. Embedding JavaScript in JSX
JSX allows embedding JavaScript expressions inside curly braces {}.
Examples:
const name = "John";
const element = <h1>Hello, {name}!</h1>;
- You can also perform calculations:
const a = 5;
const b = 10;
const element = <p>Sum: {a + b}</p>;
Call functions inside JSX:
function formatName(user) {
return user.firstName + " " + user.lastName;
}
const user = { firstName: "John", lastName: "Doe" };
const element = <h2>Hello, {formatName(user)}!</h2>;
3. Conditional Rendering in JSX
You can use JavaScript expressions for conditional content:
const isLoggedIn = true;
const message = <h1>{isLoggedIn ? "Welcome Back!" : "Please Log In"}</h1>;
Logical operators like && can also be used:
const notifications = 3;
const message = (
<div>
{notifications > 0 && <p>You have {notifications} new notifications.</p>}
</div>
);
4. Why JSX Is Useful
- Combines HTML and JavaScript in one place.
- Makes UI dynamic using expressions and functions.
- Improves code readability and maintainability.
- Automatically escapes content, preventing XSS attacks.
