What is JSX and how does it work?
JSX (JavaScript XML) is a syntax extension that lets you write HTML-like markup directly inside JavaScript. The browser doesn't understand JSX — a compiler (Babel or SWC) transforms it into React.createElement() calls before runtime.
Compiles to function calls —
<div className="x">hi</div>becomesReact.createElement("div", { className: "x" }, "hi").Expressions in braces —
{value}evaluates any JavaScript expression inline.className, htmlFor — HTML attributes renamed to avoid clashing with JS reserved words.
One root element — each return must be a single node; use Fragments (
<> ... </>) when you don't want an extra wrapper.Optional but ubiquitous — you can write React without JSX (raw
createElement) but nearly all real code uses it.New JSX transform (17+) — you no longer need
import Reactin every file; the compiler injects what it needs.Type-checked — with TypeScript, JSX gets full prop type checking via
.tsxfiles.
// JSX syntax
function Greeting({ name }) {
const isLoggedIn = true;
return (
<div className="greeting">
<h1>Hello, {name}!</h1>
{isLoggedIn && <p>Welcome back</p>}
<img src="/avatar.png" alt="Avatar" />
</div>
);
}
// What JSX compiles to (simplified):
function Greeting({ name }) {
return React.createElement('div', { className: 'greeting' },
React.createElement('h1', null, 'Hello, ', name, '!'),
isLoggedIn && React.createElement('p', null, 'Welcome back'),
React.createElement('img', { src: '/avatar.png', alt: 'Avatar' })
);
}The JSX version is clean and readable — it looks like HTML with embedded JavaScript expressions in curly braces. The compiled version shows what JSX actually produces: nested React.createElement calls.
The className attribute maps to the HTML class attribute. Conditional rendering uses && short-circuit evaluation.
Know that JSX compiles to React.createElement calls. Mention the XSS protection (auto-escaping) as a security benefit.
Understanding what JSX produces under the hood separates strong candidates.