JSX Basics
JSX is a syntax extension for JavaScript that looks like HTML but works inside your JavaScript code. It's not required to use React, but it makes writing components much more intuitive.
What is JSX?
JSX stands for JavaScript XML. It allows you to write markup directly in your JavaScript:
// This is JSX
const element = <h1>Hello, World!</h1>;
// It compiles to this JavaScript
const element = React.createElement('h1', null, 'Hello, World!');
Under the hood, JSX is just syntactic sugar for React.createElement() calls. The build tool (like Vite or Babel) transforms JSX into regular JavaScript.
JSX Rules
1. Return a Single Root Element
Components must return a single element. Use a wrapper In JSX, all tags must be closed, including self-closing ones: HTML attributes become camelCase in JSX: Use curly braces Use The Next, we'll learn how to build reusable components - the heart of React applications. Test your understanding of this lesson. <>...>):
// ❌ Wrong - multiple root elements
function Card() {
return (
<h1>Title</h1>
<p>Description</p>
);
}
// ✅ Correct - using Fragment
function Card() {
return (
<>
<h1>Title</h1>
<p>Description</p>
</>
);
}2. Close All Tags
// ✅ Self-closing tags
<img src="photo.jpg" alt="A photo" />
<input type="text" />
<br />3. Use camelCase for Attributes
// HTML: class, onclick, tabindex
// JSX: className, onClick, tabIndex
<button className="btn" onClick={handleClick}>
Click Me
</button>JavaScript Expressions in JSX
{} to embed any JavaScript expression:function Greeting({ name }) {
const today = new Date().toLocaleDateString();
return (
<div>
<h1>Hello, {name}!</h1>
<p>Today is {today}</p>
<p>2 + 2 = {2 + 2}</p>
</div>
);
}Conditional Rendering
Using Ternary Operator
function Status({ isOnline }) {
return (
<span className={isOnline ? 'text-green' : 'text-gray'}>
{isOnline ? 'Online' : 'Offline'}
</span>
);
}Using && for Conditional Display
function Notification({ count }) {
return (
<div>
{count > 0 && (
<span className="badge">{count} new messages</span>
)}
</div>
);
}Rendering Lists
map() to render arrays. Always include a unique key prop:function TodoList({ todos }) {
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>
{todo.text}
</li>
))}
</ul>
);
}key helps React identify which items changed, were added, or removed. Use unique IDs when possible, not array indices.Styling in JSX
Inline Styles (as Objects)
const buttonStyle = {
backgroundColor: 'blue',
color: 'white',
padding: '10px 20px',
borderRadius: '4px'
};
<button style={buttonStyle}>Styled Button</button>CSS Classes
import './Button.css';
<button className="btn btn-primary">Click Me</button>Key Takeaways
{} to embed JavaScript expressionsclassName instead of class, onClick instead of onclickkey props when rendering lists 🧠 Quick Quiz
What does JSX stand for?
In JSX, what attribute do you use instead of 'class' for CSS classes?
How do you embed a JavaScript expression in JSX?