JSX — JavaScript Disguised as HTML
At first glance, React code looks like ordinary HTML inserted directly into JS. But it's an illusion. In reality, it's JSX (JavaScript XML) — a special syntax that makes creating interfaces convenient.
1. The Secret Translator (Babel)
Browsers are " dumb " — they don't understand JSX. If you copy <h1>Hello</h1> into a regular JS file, the browser will throw an error.
To make it work, the bundler (Vite) uses a translator — Babel. It takes your JSX and turns it into regular JavaScript objects.
Your code:
<h1 className="title" id="main">Hello!</h1>
What the browser sees after translation:
React.createElement('h1', { className: 'title', id: 'main' }, 'Hello!');
Every tag you write turns into a function call. Eventually, React gets a tree of simple JS objects (Virtual DOM) that it can easily manage.
2. className and htmlFor: Why Not Like HTML?
In JavaScript, the words class and for are " sacred " reserved words (used for creating classes and loops).
Since JSX is JavaScript, we can't just use these words. Therefore:
- Instead of
class="btn", we writeclassName="btn". - Instead of
for="input", we writehtmlFor="input".
3. Curly Braces: A Window into the World of Logic
Inside JSX, you can open curly braces { }. This is a portal where you can write any valid JavaScript code.
But there is one ironclad rule: inside, you can only write Expressions, not Statements.
- Expression (Allowed): Something that returns a value. Math
{ 2 + 2 }, object properties{ user.name }, function calls{ getTitle() }. - Statement (Not Allowed): Commands like
if,for,while. You cannot insert a wholeforloop directly inside a button. For conditions, we use the ternary operator (a ? b : c) or the logical " AND " (&&).
4. The " Single Parent " Rule and Fragments
React is like a strict architect. It requires every component to have exactly one root (one common parent).
- ❌ Bad:
return (<h1>Hello</h1> <p>Text</p>);— React won't know which element is primary. - ✅ Good: We can wrap everything in a
<div>, but then our HTML will be cluttered with extra nested blocks ( " div-spaghetti " ).
Solution: Fragments (<></>)
These are invisible wrappers. They allow grouping a list of elements without creating extra nodes in the real DOM. In the browser, you'll see clean text without unnecessary containers.