JSX stands for JavaScript XML.
It’s a syntax extension for JavaScript that looks like HTML but is used in React to describe what the UI should look like. JSX makes it easier to write and understand the structure of React components.
Key Points about JSX:
- Looks like HTML but isn’t HTML – It gets compiled to JavaScript (
React.createElementcalls). - Must return a single parent element – wrap elements in a
<div>or<>...</>(React Fragment). - Use
{}to insert JavaScript expressions – e.g.{name},{1+2},{condition && <p>...</p>}. - Attributes use camelCase – e.g.
classNameinstead ofclass,onClickinstead ofonclick.
Example: Simple React Component with JSX
import React from "react";
function Welcome() {
const name = "Alice";
const isLoggedIn = true;
return (
<div>
<h1>Hello, {name}!</h1>
{isLoggedIn ? (
<p>Welcome back 🎉</p>
) : (
<p>Please log in to continue.</p>
)}
</div>
);
}
export default Welcome;
What happens behind the scenes?
The JSX:
<h1>Hello, {name}!</h1>
gets compiled to JavaScript:
React.createElement("h1", null, "Hello, ", name, "!");
So JSX is just syntactic sugar for writing React.createElement more cleanly.
