Understanding JSX
# 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. ); }
jsx id="ch3ex1right" // Example React component (Correct) function Header() { return ( <div> <h1>Title</h1> <p>Description</p> </div> ); }
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> ); }
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> ); }
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.