-
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:
Is transformed into JavaScript like:<h1>Hello</h1>
This means JSX is just a more readable way of writingReact.createElement("h1", null, "Hello");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:
Correct way:return <h1>Hello</h1> <p>World</p>;return ( <div> <h1>Hello</h1> <p>World</p> </div> );2. Use
classNameInstead ofclass<div className="container">Content</div>
3. JSX Uses CamelCase for Attributes
HTML attributes are written differently in JSX.
Examples:<button onClick={handleClick}>Click</button>onclick→onClicktabindex→tabIndex
4. JSX With Conditional Rendering
JSX works well with conditional logic.
This makes UI rendering dynamic and responsive to state changes.{isLoggedIn ? <Dashboard /> : <Login />}
5. JSX With Lists
Lists are commonly rendered using
.map().
Each list item needs a key to help React manage updates efficiently.const users = ["Amit", "Sara", "John"]; <ul> {users.map((user) => ( <li key={user}> {user} </li> ))} </ul>
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.