Table of Contents
What is JSX?
JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like code within your JavaScript files. It's one of React's most distinctive features and makes writing React components more intuitive and readable.
JSX Syntax Rules
JSX looks like HTML but has some important differences:
1. JSX Must Return a Single Parent Element
// ❌ Wrong - Multiple parent elements
function MyComponent() {
return (
<h1>Title</h1>
<p>Paragraph</p>
);
}
// ✅ Correct - Single parent element
function MyComponent() {
return (
<div>
<h1>Title</h1>
<p>Paragraph</p>
</div>
);
}
// ✅ Also correct - Using React Fragment
function MyComponent() {
return (
<>
<h1>Title</h1>
<p>Paragraph</p>
</>
);
}
2. JSX Attributes Use camelCase
// HTML
<div class="container" onclick="handleClick()">
// JSX
<div className="container" onClick={handleClick}>
3. Self-Closing Tags Must Be Closed
// ❌ Wrong in JSX
<img src="image.jpg">
<br>
// ✅ Correct in JSX
<img src="image.jpg" />
<br />
Embedding JavaScript in JSX
Use curly braces {} to embed JavaScript expressions:
function Greeting() {
const name = "React Developer";
const isLoggedIn = true;
const numbers = [1, 2, 3, 4, 5];
return (
<div>
<h1>Hello, {name}!</h1>
<p>Status: {isLoggedIn ? "Logged In" : "Logged Out"}</p>
<p>Current time: {new Date().toLocaleTimeString()}</p>
<ul>
{numbers.map(num => <li key={num}>{num}</li>)}
</ul>
</div>
);
}
Creating React Components
There are two main ways to create React components:
1. Function Components (Recommended)
// Simple function component
function Welcome() {
return <h1>Welcome to React!</h1>;
}
// Arrow function component
const Welcome = () => {
return <h1>Welcome to React!</h1>;
}
// Component with logic
function UserProfile() {
const user = {
name: "John Doe",
email: "john@example.com",
avatar: "/placeholder.svg?height=100&width=100"
};
return (
<div className="user-profile">
<img src={user.avatar} alt="User Avatar" />
<h2>{user.name}</h2>
<p>{user.email}</p>
</div>
);
}
2. Class Components (Legacy)
import React, { Component } from 'react';
class Welcome extends Component {
render() {
return <h1>Welcome to React!</h1>;
}
}
Component Composition
Components can use other components:
function Header() {
return (
<header>
<h1>My Website</h1>
<nav>
<a href="#home">Home</a>
<a href="#about">About</a>
<a href="#contact">Contact</a>
</nav>
</header>
);
}
function Footer() {
return (
<footer>
<p>© 2024 My Website. All rights reserved.</p>
</footer>
);
}
function App() {
return (
<div className="App">
<Header />
<main>
<h2>Welcome to our website!</h2>
<p>This is the main content area.</p>
</main>
<Footer />
</div>
);
}
Conditional Rendering
Render different content based on conditions:
function LoginStatus({ isLoggedIn, username }) {
// Using ternary operator
return (
<div>
{isLoggedIn ? (
<p>Welcome back, {username}!</p>
) : (
<p>Please log in to continue.</p>
)}
</div>
);
}
// Using logical AND operator
function Notification({ hasNewMessages, messageCount }) {
return (
<div>
{hasNewMessages && (
<div className="notification">
You have {messageCount} new messages!
</div>
)}
</div>
);
}
Styling in JSX
Multiple ways to add styles:
function StyledComponent() {
// Inline styles (object)
const buttonStyle = {
backgroundColor: "#007bff",
color: "white",
padding: "10px 20px",
border: "none",
borderRadius: "4px",
cursor: "pointer"
};
return (
<div>
{/* CSS classes */}
<div className="container">
{/* Inline styles */}
<button style={buttonStyle}>
Click Me
</button>
{/* Direct inline styles */}
<p style={{ color: "red", fontSize: "18px" }}>
Important message
</p>
</div>
</div>
);
}
Practical Exercise
Create a personal card component:
function PersonCard() {
const person = {
name: "Jane Smith",
role: "Frontend Developer",
skills: ["React", "JavaScript", "CSS", "HTML"],
experience: "3 years",
location: "San Francisco, CA"
};
return (
<div className="person-card">
<div className="card-header">
<h2>{person.name}</h2>
<p className="role">{person.role}</p>
</div>
<div className="card-body">
<p><strong>Experience:</strong> {person.experience}</p>
<p><strong>Location:</strong> {person.location}</p>
<div className="skills">
<h3>Skills:</h3>
<ul>
{person.skills.map((skill, index) => (
<li key={index}>{skill}</li>
))}
</ul>
</div>
</div>
</div>
);
}
// Use the component in App
function App() {
return (
<div className="App">
<PersonCard />
</div>
);
}
Best Practices
- Component Names: Always start with a capital letter
- File Organization: One component per file
- JSX Formatting: Use proper indentation and parentheses for multi-line JSX
- Key Prop: Always provide keys when rendering lists
- Fragment Usage: Use React.Fragment or <> to avoid unnecessary div wrappers
Summary
JSX is a powerful syntax that makes React components readable and maintainable. You've learned how to create functional components, embed JavaScript expressions, handle conditional rendering, and compose components together. In the next lesson, we'll explore props and how to pass data between components.