Skip to content

React JSX Explained — Complete Guide to JSX Syntax

DodaTech Updated 2026-06-28 6 min read

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

  1. Using class instead of className — React warns about class because it conflicts with the JavaScript class keyword. Always use className.

  2. Using if statements inside JSX — JSX only supports expressions, not statements. Use ternary operators or logical AND instead.

  3. Missing key prop in lists — React shows a warning when rendering lists without keys. Always provide a unique key for each item.

  4. Directly mutating state in JSX — JSX should read state, not modify it. Do not call state setters or mutating functions inside JSX.

  5. Boolean attributes with string valuesdisabled="false" is a string, which is truthy. Use disabled={false} with curly braces.

Practice Questions

  1. What does JSX compile to? React.createElement calls that return JavaScript objects describing the UI.

  2. How do you embed a JavaScript variable in JSX? Use curly braces: <h1>{variableName}</h1>.

  3. Why does React use className instead of class? Because class is a reserved keyword in JavaScript. JSX is closer to JavaScript than HTML.

  4. How do you conditionally render content in JSX? Use the ternary operator {condition ? <A /> : <B />} or logical AND {condition && <Component />}.

  5. What is the purpose of the key prop 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

Can I use JSX without React?

JSX is independent of React. Other tools like Vue and SolidJS support JSX, but it is most commonly associated with React.

Do I need to import React to use JSX?

In React 17+ and with the new JSX transform, you do not need import React from "react". The transform automatically imports jsx functions.

Can I write React without JSX?

Yes, using React.createElement directly. JSX is syntactic sugar that makes code more readable.

What is the `key` prop for?

React uses keys to identify elements in arrays for efficient reconciliation. Without keys, React may re-render the entire list.

Is JSX a template language?

No, JSX is JavaScript. It compiles to function calls, not string interpolation. This means you can use any JavaScript logic inside it.

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