React JSX Explained — Complete Guide to JSX Syntax
In this tutorial, you will learn about React JSX Explained. We cover key concepts, practical examples, and best practices to help you master this topic.
React JSX is a syntax extension that lets you write HTML-like markup inside JavaScript files, describing what the UI should look like in a declarative way.
What You'll Learn
- What JSX is and how it differs from HTML
- How to embed JavaScript expressions with curly braces
- How to use JSX attributes and className
- How conditional rendering works in JSX
- How JSX compiles to React.createElement
Why It Matters
JSX is the foundation of every React component. Understanding JSX means understanding how React turns your code into real DOM elements. Without JSX, React code would be verbose and hard to read.
Real-World Use
Every React file you write uses JSX. When Durga Antivirus Pro's dashboard renders a threat graph, the component returns JSX that describes the graph container, labels, and data points.
flowchart LR
A[JSX Code] --> B[Babel Compiler]
B --> C[React.createElement]
C --> D[JavaScript Objects]
D --> E[Virtual DOM]
E --> F[Real DOM]
style A fill:#3b82f6,color:#fff
What Is JSX?
JSX looks like HTML but works inside JavaScript:
function Greeting() {
return (
<div className="greeting">
<h1>Hello, React!</h1>
<p>This is JSX in action.</p>
</div>
);
}
Expected output: A div with a heading and paragraph. The className attribute replaces HTML's class.
JSX is not valid JavaScript. Babel compiles it to React.createElement calls. The above JSX becomes:
React.createElement("div", { className: "greeting" },
React.createElement("h1", null, "Hello, React!"),
React.createElement("p", null, "This is JSX in action.")
);
Embedding JavaScript Expressions
Use curly braces {} to embed any JavaScript expression:
function UserProfile({ user, isAdmin }) {
const fullName = `${user.firstName} ${user.lastName}`;
return (
<div>
<h1>Welcome, {fullName}!</h1>
<p>Email: {user.email}</p>
<p>Member since: {new Date(user.joinDate).toLocaleDateString()}</p>
<p>Role: {isAdmin ? "Administrator" : "User"}</p>
<p>Score: {user.score > 1000 ? "Expert" : "Beginner"}</p>
</div>
);
}
Expected output: A user profile with computed name, formatted date, and conditional role display.
Inside {}, you can write any JavaScript expression: variables, function calls, template literals, ternary operators, and arithmetic. You cannot write statements like if or for inside JSX.
JSX Attributes
JSX attributes follow camelCase naming:
function StyledButton({ label, onClick, disabled, icon }) {
return (
<button
onClick={onClick}
disabled={disabled}
className={`btn ${disabled ? "btn-disabled" : "btn-primary"}`}
style={{
backgroundColor: disabled ? "#ccc" : "#3b82f6",
color: "white",
padding: "10px 20px",
border: "none",
borderRadius: "4px",
cursor: disabled ? "not-allowed" : "pointer",
}}
data-testid="submit-button"
aria-label={label}
>
{icon && <span className="btn-icon">{icon}</span>}
{label}
</button>
);
}
Expected output: A styled button with icon, label, and dynamic styles. The button is disabled when disabled is true.
Key differences from HTML: className instead of class, htmlFor instead of for, onClick instead of onclick, and tabIndex instead of tabindex. The style attribute accepts a JavaScript object, not a CSS string.
Conditional Rendering
JSX does not support if statements. Use ternary operators or logical AND:
function Notification({ message, type, unreadCount }) {
return (
<div className={`notification notification-${type}`}>
{unreadCount > 0 && <span className="badge">{unreadCount}</span>}
{type === "error" ? (
<div className="error-icon">!</div>
) : (
<div className="info-icon">i</div>
)}
<p>{message}</p>
{unreadCount === 0 && <small>No new notifications</small>}
{unreadCount === 1 && <small>1 new notification</small>}
{unreadCount > 1 && <small>{unreadCount} new notifications</small>}
</div>
);
}
Expected output: A notification component that conditionally shows badges, icons, and message counts.
The && operator renders the right side only if the left side is truthy. Ternary operators choose between two expressions. For multiple conditions, chain ternaries or use separate && expressions.
Rendering Lists
Use map() to render arrays of data:
function TaskList({ tasks, onToggle, onDelete }) {
return (
<ul className="task-list">
{tasks.length === 0 ? (
<li className="empty-state">No tasks found.</li>
) : (
tasks.map(task => (
<li key={task.id} className={`task ${task.completed ? "completed" : ""}`}>
<input
type="checkbox"
checked={task.completed}
onChange={() => onToggle(task.id)}
/>
<span style={{ textDecoration: task.completed ? "line-through" : "none" }}>
{task.title}
</span>
<button onClick={() => onDelete(task.id)} className="delete-btn">
Delete
</button>
</li>
))
)}
</ul>
);
}
Expected output: A list of tasks with checkboxes and delete buttons. Shows "No tasks found" when the array is empty.
The key prop is essential when rendering lists. It helps React identify which items changed, moved, or were removed. Use a stable, unique ID. Avoid using the array index as a key if the list can be reordered.
Common Mistakes
Using
classinstead ofclassName— React warns aboutclassbecause it conflicts with the JavaScriptclasskeyword. Always useclassName.Using
ifstatements inside JSX — JSX only supports expressions, not statements. Use ternary operators or logical AND instead.Missing key prop in lists — React shows a warning when rendering lists without keys. Always provide a unique
keyfor each item.Directly mutating state in JSX — JSX should read state, not modify it. Do not call state setters or mutating functions inside JSX.
Boolean attributes with string values —
disabled="false"is a string, which is truthy. Usedisabled={false}with curly braces.
Practice Questions
What does JSX compile to?
React.createElementcalls that return JavaScript objects describing the UI.How do you embed a JavaScript variable in JSX? Use curly braces:
<h1>{variableName}</h1>.Why does React use
classNameinstead ofclass? Becauseclassis a reserved keyword in JavaScript. JSX is closer to JavaScript than HTML.How do you conditionally render content in JSX? Use the ternary operator
{condition ? <A /> : <B />}or logical AND{condition && <Component />}.What is the purpose of the
keyprop in lists? To help React identify which items changed, moved, or were removed for efficient DOM updates.
Challenge
Build a CatalogGrid component that receives an array of products (each with id, name, price, imageUrl, inStock). Use JSX to render a responsive grid. Show a "Sold Out" overlay on out-of-stock items. Display the price formatted with a currency sign. Show a "No products match your criteria" message when the array is empty.
FAQ
Mini Project
Build a ProductCatalogJSX component. Use JSX to render a product grid with images, prices, and ratings. Implement conditional rendering for out-of-stock badges and "Featured" tags. Use map() to render the product list. Add sorting buttons (by price, rating, name) that re-render the list. Use inline styles for all styling to practice JSX style syntax.
What's Next
Continue with React components and props:
React Components, React Props, React State
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro