ReactJS JSX

While learning React, one of the first things you notice is that JavaScript code looks like HTML. This syntax is called JSX. Understanding JSX is essential because almost every React application uses it to describe the user interface.

What Is JSX?

JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like code inside JavaScript files.

Example:

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

Even though it looks like HTML, JSX is not HTML. It is syntax that gets converted into JavaScript behind the scenes.

Instead of separating HTML and JavaScript, JSX allows React to combine them in a clean and organized way.


How JSX Works Behind the Scenes?

JSX does not run directly in the browser. It is converted into JavaScript using tools like Babel.

JSX Code:

<h1>Hello</h1>

Is transformed into JavaScript like:

React.createElement("h1", null, "Hello");

This means JSX is just a more readable way of writing React.createElement() calls.

JSX Rules Every Developer Should Know

JSX follows some important rules that are different from HTML.

1. JSX Must Return a Single Parent Element

All tags must be inside a parent div.

Incorrect way:

return 
<h1>Hello</h1>
<p>World</p>;

Correct way:

return (
  <div>
    <h1>Hello</h1>
    <p>World</p>
  </div>
);

2. Use className Instead of class


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


3. JSX Uses CamelCase for Attributes

HTML attributes are written differently in JSX.


<button onClick={handleClick}>Click</button>

Examples:
  • onclickonClick
  • tabindextabIndex

4. JSX With Conditional Rendering

JSX works well with conditional logic.

{isLoggedIn ? <Dashboard /> : <Login />}

This makes UI rendering dynamic and responsive to state changes.

5. JSX With Lists

Lists are commonly rendered using .map().


const users = ["Amit", "Sara", "John"];

<ul>
  {users.map((user) => (
    <li key={user}>
      {user}
    </li>
  ))}
</ul>

Each list item needs a key to help React manage updates efficiently.

Summary

JSX is a powerful and essential part of React. It allows developers to write UI code in a clean, readable, and structured way using JavaScript.

Once you understand JSX, learning Props, State, Events, and Hooks becomes much easier because JSX is the foundation of React’s UI system.