Skip to main content
React Introduction
CHAPTER 03 Beginner

Understanding JSX

Updated: May 13, 2026
20 min read

# Understanding JSX

1. Introduction

If you looked at the code in the previous chapter, you might have thought, *"Why is there HTML inside my JavaScript file?"* Welcome to JSX! JSX stands for JavaScript XML. It is a syntax extension for JavaScript that allows you to write HTML-like markup directly inside your React components. In this chapter, we will master the rules of JSX and learn how it bridges the gap between logic and UI.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Explain what JSX is and why React uses it.
  • Understand the core rules of writing valid JSX.
  • Embed JavaScript expressions (variables, functions, math) inside JSX.
  • Render dynamic HTML elements.
  • Convert standard HTML into React JSX.

3. Beginner-Friendly Explanations

What is JSX?

Traditionally, web developers separated their code into three files: HTML for structure, CSS for styling, and JavaScript for logic. React changed this paradigm. Instead of putting JavaScript into HTML, React puts HTML into JavaScript! JSX is just "syntactic sugar". Under the hood, React converts JSX into standard JavaScript objects using tools like Babel.

Why Use JSX?

JSX makes your code easier to read and write. It visually represents the UI while allowing you to harness the full power of JavaScript right alongside the markup.

4. The 3 Golden Rules of JSX

Rule 1: Return a Single Root Element

A component must always return one wrapping element. You cannot return two sibling elements side-by-side.

Wrong: ```jsx id="ch3ex1wrong" // Example React component (Incorrect) function Header() { return ( <h1>Title</h1> <p>Description</p> // Error! Two root elements. ); }

1
**Right:**

jsx id="ch3ex1right" // Example React component (Correct) function Header() { return ( <div> <h1>Title</h1> <p>Description</p> </div> ); }

123456789101112131415
*Note: If you don't want to add an extra `<div>` to your real DOM, you can use a "Fragment" `<> ... </>`.*

### Rule 2: Close All Tags
In standard HTML, some tags like `<img>` or `<input>` don't need a closing tag. In JSX, **every** tag must be closed.
- HTML: `<img src="logo.png">`
- JSX: `<img src="logo.png" />` (Notice the trailing slash)

### Rule 3: camelCase for Attributes
JSX is closer to JavaScript than HTML. Since `class` is a reserved word in JavaScript, JSX uses `className` instead. Multi-word HTML attributes use camelCase.
- HTML: `<div class="container" onclick="doSomething()">`
- JSX: `<div className="container" onClick={doSomething}>`

## 5. Embedding JavaScript Expressions
The superpower of JSX is the curly braces `{}`. Anything inside curly braces is treated as pure JavaScript. You can embed variables, perform math, or call functions.

jsx id="ch3_ex2" // Example React component function UserGreeting() { const name = "Alice"; const age = 25; const isOnline = true;

return ( <div> {/* Rendering variables */} <h2>Hello, {name}!</h2> {/* Performing math */} <p>In 5 years, you will be {age + 5}.</p> {/* Using JavaScript methods */} <p>Your name in uppercase is: {name.toUpperCase()}</p> {/* Converting booleans to strings to display them */} <p>Status: {String(isOnline)}</p> </div> ); }

12345678910
## 6. Output Explanations
When React renders the `UserGreeting` component:
1. `{name}` is replaced with "Alice".
2. `{age + 5}` calculates `25 + 5` and outputs "30".
3. `{name.toUpperCase()}` evaluates to "ALICE".
4. `{String(isOnline)}` outputs "true". (Note: React does not render booleans directly to the screen; you must convert them to a string or use them for conditional logic).

## 7. Real-World Examples
Imagine an e-commerce product card. You need to display the product name, calculate a discount, and show an image.

jsx id="ch3_ex3" // Example React component function ProductCard() { const product = { title: "Wireless Headphones", price: 100, discount: 0.20, imageUrl: "https://example.com/headphones.jpg" };

const finalPrice = product.price - (product.price * product.discount);

return ( <div className="product-card"> <img src={product.imageUrl} alt={product.title} className="product-image" /> <h3>{product.title}</h3> <p className="original-price">Was: ${product.price}</p> <p className="discounted-price">Now: ${finalPrice}</p> </div> ); }

12345678910111213141516
## 8. Common Mistakes
- **Putting objects directly in curly braces:** React cannot render a full JavaScript object directly to the screen. `{product}` will throw an error. You must access specific properties like `{product.title}`.
- **Forgetting the Fragment:** Attempting to return a list of `<li>` tags without wrapping them in a `<ul>` or `<>` fragment.
- **Using `class` instead of `className`:** A very common beginner mistake. The code will still work, but you will get warnings in the browser console.

## 9. Best Practices
- Keep JSX clean and readable. If the JSX inside a component gets too long (over 50-100 lines), it's time to break it down into smaller components.
- Use Fragments `<></>` to avoid "div soup" (an unnecessarily deep HTML tree with useless wrapper divs).

## 10. Exercises
1. Create a JSX element that displays your first name and last name stored in two different variables.
2. Write a JSX image tag. Ensure it is self-closing and uses a dynamic URL from a variable.

## 11. Mini Project: User Profile JSX Card
Let's build a static user profile card utilizing everything we've learned about JSX.

jsx id="ch3_proj1" // Example React component function UserProfile() { const user = { firstName: "Sarah", lastName: "Connor", role: "Software Engineer", company: "Cyberdyne", avatar: "https://i.pravatar.cc/150?img=47" };

return ( <div className="bg-white shadow-lg rounded-xl p-6 max-w-sm mx-auto mt-10 text-center border border-gray-200"> <img src={user.avatar} alt={${user.firstName} ${user.lastName}} className="w-24 h-24 rounded-full mx-auto border-4 border-blue-500 mb-4" /> <h2 className="text-2xl font-bold text-gray-800"> {user.firstName} {user.lastName} </h2> <p className="text-blue-600 font-semibold">{user.role}</p> <p className="text-gray-500 text-sm mt-1">@ {user.company}</p> <div className="mt-6"> <button className="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-6 rounded-full transition-colors duration-300"> Connect </button> </div> </div> ); } ``

12. Coding Challenges

Challenge 1: Create a component called
MathQuiz. Define two variables, num1 and num2. Render a string that says "What is [num1] + [num2]?". Below it, render the correct answer using JSX evaluation.

13. MCQs with Answers

Q1: What is the correct way to add a CSS class in JSX? A) class="btn" B) css="btn" C) className="btn" D) style="btn" *Answer: C*

Q2: What happens if you try to return two sibling <div> tags directly from a component without a wrapper? A) React renders both sequentially. B) React throws a syntax error. C) React merges them into one <div>. D) React ignores the second <div>. *Answer: B*

14. Interview Questions

  • Q: How is JSX different from HTML?
  • Q: Why do we need to import React in older versions of React to use JSX? *(Answer: Because JSX compiles to React.createElement)*
  • Q: What is a React Fragment and why is it useful?

15. FAQs

Can I write
if statements inside JSX {}? No. You cannot write if...else statements directly inside JSX curly braces because they are statements, not expressions. However, you *can* use the ternary operator (condition ? true : false) which we will cover in the Conditional Rendering chapter.

16. Summary

JSX is a powerful syntax extension that allows you to write UI markup seamlessly within your JavaScript logic. By following the three golden rules (single root element, close all tags, camelCase attributes) and mastering curly braces
{}`, you can build dynamic, data-driven interfaces.

17. Next Chapter Recommendation

Now that you can write JSX, it's time to learn how to organize it. In Chapter 4: React Components Basics, we will explore the heart of React: breaking UI down into reusable, independent components.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·