Chapter 3: JSX Syntax
Chapter 3 of 15
Chapter 3: JSX Syntax
3.1 What is JSX?
JSX (JavaScript XML) is a syntax extension that allows you to write HTML-like code in JavaScript. It makes React code more readable and intuitive.
JSX Characteristics:
- Looks like HTML but is JavaScript
- Gets compiled to React.createElement() calls
- Allows embedding JavaScript expressions
- Makes component code more readable
// JSX
const element = <h1>Hello, World!</h1>;
// Compiles to:
const element = React.createElement('h1', null, 'Hello, World!');
Why JSX?
- More intuitive than createElement calls
- Visual representation of UI structure
- Better developer experience
- Type checking and autocomplete support
3.2 JSX Rules
JSX has specific rules that must be followed for correct compilation.
Embedding Expressions:
const name = "John";
const age = 30;
// Embed variables
const greeting = <h1>Hello, {name}!</h1>;
// Embed expressions
const info = <p>Age: {age + 1}</p>;
// Embed function calls
const message = <p>{getGreeting(name)}</p>;
// Embed conditionals
const status = <p>{isLoggedIn ? 'Welcome' : 'Please login'}</p>;
JSX Rules:
- Return single root element (or Fragment)
- Use className instead of class
- Use camelCase for attributes (onClick, not onclick)
- Close all tags (self-closing: <img />)
- Use {} for JavaScript expressions
// Single root element
const element = (
<div>
<h1>Title</h1>
<p>Content</p>
</div>
);
// Or use Fragment
const element = (
<>
<h1>Title</h1>
<p>Content</p>
</>
);
// Attributes
<div className="container" onClick={handleClick}>
<img src="image.jpg" alt="Description" />
</div>
3.3 JSX Expressions
JSX supports various JavaScript expressions.
// Variables
const name = 'John';
<p>{name}</p>
// Calculations
<p>Total: {price * quantity}</p>
// Function calls
<p>{formatDate(new Date())}</p>
// Ternary operator
<div>{isActive ? 'Active' : 'Inactive'}</div>
// Logical AND
{isLoading && <Spinner />}
// Array methods
<ul>
{items.map(item => <li key={item.id}>{item.name}</li>)}
</ul>
3.4 JSX Best Practices
Follow best practices for clean, maintainable JSX.
- Keep JSX readable and formatted
- Extract complex logic outside JSX
- Use meaningful variable names
- Break complex JSX into smaller components
- Use fragments to avoid unnecessary divs