JSX (JavaScript XML) is a JavaScript syntax extension that allows writing HTML-like code directly inside JS files.
Simple analogy: Previously you had to write in pure JavaScript:
1const button = document.createElement('button');2button.textContent = 'Click me';3button.className = 'btn';4button.onclick = () => alert('Hello!');
This is like making a sandwich by instruction: "Take bread, put ham on it..."
With JSX you simply write:
1const button = <button className="btn" onClick={() => alert('Hello!')}>Click me</button>;
This is like getting a ready-made sandwich immediately.
Another analogy: JSX is like a universal translator for your brain. You think in visual terms ("I want a heading here, a button there"), but JavaScript speaks in function calls and objects. JSX bridges this gap — you write what you see, and the compiler translates it into what JavaScript understands.
How it works: JSX is not understood by the browser. Babel (tool) transforms JSX into regular JavaScript:
1// What you write:2const element = <h1>Hello, {name}!</h1>;34// What it becomes:5const element = React.createElement('h1', null, `Hello, ${name}!`);67// And for nested elements:8const element = (9 <div className="container">10 <h1>Hello</h1>11 <p>World</p>12 </div>13);1415// Becomes:16const element = React.createElement(17 'div',18 { className: "container" },19 React.createElement('h1', null, 'Hello'),20 React.createElement('p', null, 'World')21);
JSX Rules:
<h1>{title}</h1>.<br />.style={{ color: "red" }}.{/* */} syntax inside JSX.Why it matters:
Common mistakes:
if/else statements directly, only ternary operators or &&.class instead of className, or for instead of htmlFor.<>...</>).onclick (camelCase required: onClick).Advanced JSX patterns:
1// Conditional rendering2{isLoggedIn ? <Dashboard /> : <LoginPage />}3{error && <ErrorMessage message={error} />}45// Dynamic tag names6const tag = "h1";7const DynamicTag = tag; // <DynamicTag>Hello</DynamicTag>89// Spreading props10const props = { className: "btn", onClick: handleClick };11<button {...props}>Click</button>
JSX is not required — you can write in pure createElement, but JSX is more convenient and clear. In practice, virtually every React project uses JSX.