ReactEasy
What is JSX in React? How is it different from HTML?
JSX is a syntax extension that lets you write HTML-like code inside JavaScript. The compiler (Babel or SWC) transforms it into regular React.createElement(...) calls.
The transform
// What you write
const greeting = <h1 className="title">Hello, {name}</h1>;
// What the browser actually runs
const greeting = React.createElement('h1', { className: 'title' }, 'Hello, ', name);
JSX is not HTML. It's a JavaScript expression that evaluates to a plain object describing what to render.
Key differences from HTML
| HTML | JSX | Why |
|---|---|---|
class="x" | className="x" | class is a reserved word in JS |
for="x" | htmlFor="x" | for is a JS keyword |
onclick="..." | onClick={fn} | camelCase + JS expression, not a string |
style="color:red" | style={{ color: 'red' }} | object, not string |
| Self-closing optional | Required: <img />, <br /> | XML-like |
| Text + tags | Must have one root | (or a fragment) |
Embedding JavaScript
const user = { name: 'Alice', age: 30 };
return (
<div>
<p>Hello {user.name}, you are {user.age}</p>
<p>{user.age >= 18 ? 'Adult' : 'Minor'}</p>
<ul>
{['a', 'b', 'c'].map((x) => <li key={x}>{x}</li>)}
</ul>
</div>
);
Anything inside { } is a JS expression. Statements (if/for/while) don't work directly — use ternaries, &&, or .map().
Fragments — multiple root elements
// ❌ Two roots — syntax error
return <h1>Title</h1><p>Body</p>;
// ✅ Wrap in a fragment
return (
<>
<h1>Title</h1>
<p>Body</p>
</>
);
Fragments produce no DOM node — useful when you must return adjacent elements without an extra <div>.
Common gotchas
// ❌ Always renders 0 when count is 0
{count && <Badge>{count}</Badge>}
// ✅ Boolean-coerce
{count > 0 && <Badge>{count}</Badge>}
JSX renders 0 (a number) but skips false, null, undefined. So 0 && ... evaluates to 0 and React happily prints "0" on screen.
Why JSX, not template strings?
- IDE support — autocomplete, type-checking via TypeScript
- Compile-time errors for bad markup
- Lets you compose components like functions:
<Button><Icon /></Button>
TypeScript + JSX = TSX
Same rules; file extension is .tsx. Lets you type props:
function Greeting({ name }: { name: string }) {
return <h1>Hello, {name}</h1>;
}