JSX (JavaScript XML) is a syntax extension that lets you write HTML-like markup inside JavaScript. It is not required to use React, but it is the standard way almost everyone writes it. Under the hood, a build tool (Babel/Vite) compiles JSX into plain React.createElement() calls.
const element = <h1>Hello, world!</h1>;
// compiles roughly to:
const element = React.createElement('h1', null, 'Hello, world!');
Embedding JavaScript expressions
Anything inside curly braces {} is evaluated as a JavaScript expression:
const name = 'Rahim';
const element = <h1>Hello, {name}!</h1>;
const sum = <p>2 + 2 = {2 + 2}</p>;
JSX rules that differ from HTML
- One root element — wrap sibling elements in a parent, or use a Fragment.
function Profile() {
return (
<>
<h2>Rahim Uddin</h2>
<p>Software Engineer</p>
</>
);
}
classNameinstead ofclass,htmlForinstead offor— becauseclassandforare reserved words in JavaScript.
<label htmlFor="email" className="form-label">Email</label>
-
camelCase attributes —
onClick,tabIndex,strokeWidth, notonclick,tabindex. -
Every tag must be closed —
<img />,<br />,<input />are self-closing. -
Inline styles are objects, not strings, and property names are camelCase:
<div style={{ backgroundColor: 'tomato', fontSize: 20 }}>Styled</div>
- Comments need curly braces:
{/* this is a JSX comment */}
Conditional rendering inside JSX
function Greeting({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? <p>Welcome back!</p> : <p>Please sign in.</p>}
{isLoggedIn && <button>Log out</button>}
</div>
);
}