Paramclasses Academy - Blog

Tutorials Details

←
Post 4 of 29
→

What is JSX: Syntax, Rules, Expressions, in React.js ?

What is JSX: Syntax, Rules, Expressions, in React.js ?

October 28, 2026

1. Introduction

JSX stands for JavaScript XML. It is a syntax extension for JavaScript that allows developers to write HTML-like markup inside JavaScript code.

In React applications, JSX makes it easier to describe how the user interface should look. Instead of writing complex UI structures using JavaScript function calls, developers can use a familiar, HTML-like syntax.

For example:

function App() {
  return <h1>Welcome to React!</h1>;
}

export default App;

Here, <h1>Welcome to React!</h1> is JSX. It describes a heading that React can render on the screen.

Important: JSX is not exactly HTML. It looks similar to HTML, but it follows specific rules and is transformed into JavaScript by tools such as Vite's build tooling.

2. Learning Objectives

By the end of this tutorial, you will be able to:

  • Understand JSX and why React developers use it.

  • Write JSX inside functional components.

  • Follow JSX syntax rules.

  • Embed JavaScript expressions inside JSX.

  • Use variables and expressions to display dynamic content.

  • Apply JSX attributes such as className.

  • Render multiple elements correctly.

  • Follow JSX best practices and avoid common errors.

3. Core Concepts and Explanation

3.1 What Is JSX?

JSX allows you to write UI markup directly within JavaScript.

Without JSX, creating a React element requires a function such as React.createElement(). JSX provides a more readable way to describe the same UI.

With JSX:

const heading = <h1>Hello, React!</h1>;

Conceptually, a JSX transformation converts this markup into JavaScript calls that create React elements. Modern React build tools commonly use the automatic JSX runtime, so you do not need to import React merely to write JSX.

3.2 JSX vs. HTML

JSX resembles HTML, but some syntax differs.

HTML JSX
class="title" className="title"
for="email" htmlFor="email"
<img> <img />
<br> <br />
Inline style uses a CSS string Inline style uses a JavaScript object

Example:

function App() {
  return (
    <div className="container">
      <label htmlFor="username">Username</label>
      <input id="username" type="text" />
      <img src="/logo.png" alt="Website logo" />
    </div>
  );
}

export default App;

Why use className? JSX uses JavaScript-oriented property names for many attributes. Therefore, React uses className for CSS classes.

3.3 JSX Must Have One Root Element

A component's returned JSX must have one root element.

Incorrect:

function App() {
  return (
    <h1>Hello</h1>
    <p>Welcome to React.</p>
  );
}

This produces a syntax error because there are two sibling root elements.

Correct:

function App() {
  return (
    <div>
      <h1>Hello</h1>
      <p>Welcome to React.</p>
    </div>
  );
}

export default App;

You can also use a React Fragment when you do not want to add an extra HTML element.

function App() {
  return (
    <>
      <h1>Hello</h1>
      <p>Welcome to React.</p>
    </>
  );
}

export default App;

The <>...</> syntax is a shorthand for a Fragment. It groups elements without creating an additional DOM wrapper.

3.4 Close Every JSX Tag

JSX requires elements to be properly closed.

Incorrect:

<img src="/logo.png">
<input type="text">

Correct:

<img src="/logo.png" alt="Logo" />
<input type="text" />

Self-closing syntax is required for elements that do not have closing tags.

3.5 JSX Uses JavaScript Expressions Inside Curly Braces

Use {} to embed a JavaScript expression inside JSX.

Example:

function App() {
  const name = "Rahul";
  const age = 22;

  return (
    <div>
      <h1>Hello, {name}!</h1>
      <p>Your age is {age}.</p>
      <p>Next year, you will be {age + 1}.</p>
    </div>
  );
}

export default App;

Expected output:

Hello, Rahul!
Your age is 22.
Next year, you will be 23.

Expressions can include:

  • Variables

  • Mathematical calculations

  • Function calls that return values

  • Ternary expressions

  • Array methods such as map()

A JavaScript statement such as if or for cannot be placed directly inside JSX braces as an expression. Use the appropriate JavaScript logic outside the JSX or an expression such as a ternary operator inside it.

3.6 Display Dynamic Data in JSX

JSX can display data from variables instead of using fixed text.

function App() {
  const product = "Wireless Headphones";
  const price = 2499;

  return (
    <div>
      <h1>{product}</h1>
      <p>Price: ₹{price}</p>
    </div>
  );
}

export default App;

Expected output:

Wireless Headphones
Price: ₹2499

This is useful for product listings, profile pages, dashboards, and other interfaces that display data.

3.7 Use Conditional Expressions in JSX

A ternary expression can choose which content to display.

function App() {
  const isLoggedIn = true;

  return (
    <div>
      <h1>{isLoggedIn ? "Welcome Back!" : "Please Log In"}</h1>
    </div>
  );
}

export default App;

Because isLoggedIn is true, the heading displays Welcome Back!.

For more complex conditional rendering, you can use if statements before the return statement.

3.8 Use JavaScript Expressions in Attributes

Curly braces can also provide dynamic attribute values.

function App() {
  const imageUrl = "/logo.png";
  const imageDescription = "Company logo";

  return (
    <img src={imageUrl} alt={imageDescription} />
  );
}

export default App;

For a dynamic CSS class:

function App() {
  const isActive = true;

  return (
    <button className={isActive ? "active" : "inactive"}>
      Continue
    </button>
  );
}

export default App;

Here, className receives the value "active" because isActive is true.

3.9 Inline Styles in JSX

In JSX, the style attribute accepts a JavaScript object rather than a CSS string.

function App() {
  const headingStyle = {
    color: "blue",
    fontSize: "32px",
    textAlign: "center"
  };

  return (
    <h1 style={headingStyle}>Learn JSX</h1>
  );
}

export default App;

Notice that:

  • CSS property names use camelCase, such as fontSize.

  • The style value is a JavaScript object.

  • String values such as "blue" and "32px" are enclosed in quotes.

  • The object is passed inside curly braces.

For larger applications, regular CSS files or CSS modules are often easier to maintain than extensive inline styles.

3.10 Render Lists Using JSX

JSX works with JavaScript array methods such as map().

function App() {
  const courses = ["HTML", "CSS", "JavaScript", "React"];

  return (
    <div>
      <h1>Our Courses</h1>

      <ul>
        {courses.map((course) => (
          <li key={course}>{course}</li>
        ))}
      </ul>
    </div>
  );
}

export default App;

Expected output:

  • HTML

  • CSS

  • JavaScript

  • React

The key attribute helps React identify list items when the list changes. For real-world data, prefer a stable unique ID from the data rather than an array index when possible.

4. Practical Code Examples

Example 1: Create Your First JSX Component

Open your React project in VS Code and edit src/App.jsx:

function App() {
  return (
    <div>
      <h1>Welcome to Param Classes</h1>
      <p>Learn React step by step.</p>
    </div>
  );
}

export default App;

Save the file and run your project:

npm run dev

Open the local URL shown in your terminal. You should see the heading and paragraph in the browser.

Example 2: JSX With Variables and Calculations

Replace the content of src/App.jsx with:

function App() {
  const studentName = "Rahul";
  const courseName = "React.js";
  const completedLessons = 4;
  const totalLessons = 30;

  return (
    <div>
      <h1>Student Dashboard</h1>
      <p>Student: {studentName}</p>
      <p>Course: {courseName}</p>
      <p>
        Progress: {completedLessons} out of {totalLessons} lessons
      </p>
      <p>
        Completion: {Math.round(
          (completedLessons / totalLessons) * 100
        )}%
      </p>
    </div>
  );
}

export default App;

Expected output includes:

Student Dashboard
Student: Rahul
Course: React.js
Progress: 4 out of 30 lessons
Completion: 13%

This example demonstrates how JSX combines static markup with dynamic JavaScript values.

Example 3: JSX With a Conditional Message

function App() {
  const hasCompletedCourse = false;

  return (
    <div>
      <h1>Course Status</h1>

      <p>
        {hasCompletedCourse
          ? "Congratulations! You completed the course."
          : "Keep learning. You are making progress!"}
      </p>
    </div>
  );
}

export default App;

Because hasCompletedCourse is false, the second message appears.

Example 4: JSX With a Reusable Data List

function App() {
  const students = [
    { id: 1, name: "Rahul" },
    { id: 2, name: "Priya" },
    { id: 3, name: "Aman" }
  ];

  return (
    <div>
      <h1>Students</h1>

      <ul>
        {students.map((student) => (
          <li key={student.id}>{student.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default App;

This example introduces a common pattern used in React applications: mapping data into a collection of UI elements.

5. Real-World Applications

JSX is used throughout modern React applications.

E-commerce website: Display product names, prices, images, ratings, and availability.

Admin dashboard: Display user information, sales figures, statistics, and status labels.

Learning management system: Show student names, course progress, lesson lists, and completion messages.

Authentication interface: Display different content depending on whether a user is logged in.

API-driven application: Render lists of products, articles, users, or other records retrieved from a server.

In each case, JSX combines the UI structure with the JavaScript data and logic needed to display it.

6. Common Mistakes and Best Practices

Common Mistakes

Mistake 1: Using class instead of className

Incorrect:

<div class="container">Hello</div>

Correct:

<div className="container">Hello</div>

Mistake 2: Returning multiple root elements

Incorrect:

return (
  <h1>Title</h1>
  <p>Description</p>
);

Correct:

return (
  <>
    <h1>Title</h1>
    <p>Description</p>
  </>
);

Mistake 3: Forgetting to close tags

Incorrect:

<img src="/logo.png">

Correct:

<img src="/logo.png" alt="Logo" />

Mistake 4: Using JavaScript variables without curly braces

Incorrect:

const name = "Rahul";

return <h1>name</h1>;

This displays the literal word name.

Correct:

const name = "Rahul";

return <h1>{name}</h1>;

Mistake 5: Using a CSS string in the style attribute

Incorrect:

<h1 style="color: blue">Hello</h1>

Correct:

<h1 style={{ color: "blue" }}>Hello</h1>

Mistake 6: Omitting keys from mapped lists

Incorrect:

{courses.map((course) => (
  <li>{course}</li>
))}

Correct:

{courses.map((course) => (
  <li key={course}>{course}</li>
))}

Use a stable, unique identifier for each item whenever possible.

Best Practices

  • Keep JSX readable with consistent indentation.

  • Break large UI sections into reusable components.

  • Use meaningful variable and component names.

  • Use className and valid JSX attributes.

  • Use {} for JavaScript expressions.

  • Use Fragments when an extra DOM element is unnecessary.

  • Provide stable keys when rendering lists.

  • Keep complex calculations and business logic outside large JSX expressions.

  • Use semantic HTML elements such as main, section, nav, and button appropriately.

  • Add descriptive alt text to meaningful images.

  • Avoid inserting untrusted HTML directly into the DOM.

7. Practice Exercises

Complete these exercises yourself before checking the next tutorial.

Exercise 1: Create a JSX component that displays your name, age, and city.

Exercise 2: Create a course card displaying the course name, price, and duration using JavaScript variables.

Exercise 3: Create a conditional message that displays "You are eligible" when a variable is true and "You are not eligible" when it is false.

Exercise 4: Create an array containing five programming languages and display them in an unordered list using map() and appropriate keys.

Exercise 5: Create a profile component containing a heading, an image, a paragraph, and a button. Use className for CSS styling.

Challenge: Create a simple student dashboard displaying a student's name, course, completed lessons, total lessons, and calculated completion percentage.

8. Key Takeaways and Conclusion

In this tutorial, you learned that:

  • JSX is a JavaScript syntax extension used to describe React user interfaces.

  • JSX looks similar to HTML but follows React-specific syntax rules.

  • A component must return one root element, which can be a Fragment.

  • JSX elements must be properly closed.

  • Curly braces allow JavaScript expressions inside JSX.

  • Dynamic values can be used in content and attributes.

  • Inline styles use JavaScript objects.

  • The map() method can render lists, and list items should have stable keys.

Final advice: Do not memorize JSX rules without practicing them. Build small components, intentionally test common mistakes, and learn to read the errors your development tools display.

←
Post 4 of 29
→