JSX Syntax
Master JSX syntax with comprehensive understanding of its features, rules, and best practices. Learn how to write clean, readable, and efficient React components using JSX. This is a foundational concept in component-based UI development that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world React experience. Take your time with each section and practice the examples
Understanding JSX Fundamentals
JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like code in your JavaScript files. It makes React components more readable and easier to write by combining the power of JavaScript with the familiar syntax of HTML. JSX gets transpiled to regular JavaScript function calls, making it both powerful and performant.
JSX Core Rules and Best Practices
- Single Root Element: JSX expressions must have one parent element (use React.Fragment or <> for multiple elements)
- Self-Closing Tags: All tags must be properly closed, including self-closing tags like <img />
- camelCase Attributes: HTML attributes use camelCase (className, onClick, onMouseOver)
- JavaScript Expressions: Use curly braces {} for JavaScript expressions and variables
- Reserved Keywords: Avoid using reserved JavaScript keywords as prop names
- Conditional Rendering: Use logical operators (&&, ||) or ternary operators for conditional rendering
Basic JSX Examples
// Basic JSX element
const element = <h1>Hello, World!</h1>;
// JSX with JavaScript expressions
const user = {
name: 'John',
age: 30
};
const greeting = <h1>Hello, {user.name}!</h1>;
// JSX with attributes
const element = <div className="container">Content</div>;
// JSX with children
const element = (
<div>
<h1>Title</h1>
<p>Paragraph</p>
</div>
);JSX with Conditional Rendering
// Conditional rendering with ternary operator
function Greeting({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? (
<h1>Welcome back!</h1>
) : (
<h1>Please sign in.</h1>
)}
</div>
);
}
// Conditional rendering with logical AND
function Mailbox({ unreadMessages }) {
return (
<div>
<h1>Hello!</h1>
{unreadMessages.length > 0 && (
<h2>You have {unreadMessages.length} unread messages.</h2>
)}
</div>
);
}
// Conditional rendering with variables
function LoginButton({ isLoggedIn }) {
let button;
if (isLoggedIn) {
button = <LogoutButton />;
} else {
button = <LoginButton />;
}
return <div>{button}</div>;
}Advanced JSX Patterns
// JSX with arrays and mapping
function UserList({ users }) {
return (
<div>
<h2>User List</h2>
<ul>
{users.map(user => (
<li key={user.id}>
<strong>{user.name}</strong> - {user.email}
</li>
))}
</ul>
</div>
);
}
// JSX with fragments
function UserProfile({ user }) {
return (
<>
<h1>{user.name}</h1>
<p>{user.email}</p>
<p>{user.bio}</p>
</>
);
}
// JSX with event handlers
function Button({ onClick, children }) {
return (
<button
onClick={onClick}
className="btn btn-primary"
style={{ padding: '10px 20px' }}
>
{children}
</button>
);
}
// JSX with dynamic attributes
function DynamicElement({ tag, children, ...props }) {
const Tag = tag;
return <Tag {...props}>{children}</Tag>;
}
// Usage
<DynamicElement tag="h1" className="title">Dynamic Title</DynamicElement>
<DynamicElement tag="p" style={{ color: 'blue' }}>Dynamic paragraph</DynamicElement>Practice Exercise: JSX Components
// Exercise: Build a Product Card Component
// Create a reusable product card component using JSX
// src/components/ProductCard.js
import React from 'react';
function ProductCard({ product }) {
const { name, price, image, rating, inStock } = product;
return (
<div className="product-card">
<img src={image} alt={name} className="product-image" />
<div className="product-info">
<h3>{name}</h3>
<p className="price">{price}</p>
<div className="rating">
{[...Array(5)].map((_, index) => (
<span
key={index}
className={index < rating ? 'star filled' : 'star'}
>
★
</span>
))}
<span className="rating-text">({rating}/5)</span>
</div>
<div className="stock-status">
{inStock ? (
<span className="in-stock">In Stock</span>
) : (
<span className="out-of-stock">Out of Stock</span>
)}
</div>
<button
className="add-to-cart"
disabled={!inStock}
>
{inStock ? 'Add to Cart' : 'Sold Out'}
</button>
</div>
</div>
);
}
// Usage in App.js
const products = [
{
id: 1,
name: "Wireless Headphones",
price: 99.99,
image: "/images/headphones.jpg",
rating: 4,
inStock: true
},
{
id: 2,
name: "Smart Watch",
price: 199.99,
image: "/images/smartwatch.jpg",
rating: 5,
inStock: false
}
];
function App() {
return (
<div className="App">
<h1>Product Catalog</h1>
<div className="products-grid">
{products.map(product => (
<ProductCard key={product.id} product={product} />
))}
</div>
</div>
);
}
// Challenge: Add a search filter
// Challenge: Add sorting by price or rating
// Challenge: Add a shopping cart functionality