JSX
What is JSX?
JSX (JavaScript XML) is a syntax extension that lets you write HTML markup inside JavaScript code. JSX is not HTML — it is compiled into React.createElement() calls by tools like Babel.
// JSX
const element = <h1>Hello, World!</h1>;
// Compiled output
const element = React.createElement('h1', null, 'Hello, World!');
Writing Markup with JSX
JSX looks like HTML but is written inside JavaScript. Every React component returns JSX.
function Card() {
return (
<div className="card">
<h2>Card Title</h2>
<p>This is the card content.</p>
</div>
);
}
Expressions in JSX
Use curly braces {} to write JavaScript expressions inside JSX.
function Profile({ name, age }) {
return (
<div>
<h1>Name: {name}</h1>
<p>Age: {age} years</p>
<p>2 + 3 = {2 + 3}</p>
<p>This year: {new Date().getFullYear()}</p>
</div>
);
}
Attributes: className vs class
In JSX, use className instead of class because class is a reserved word in JavaScript.
// Wrong
<div class="container">...</div>
// Correct
<div className="container">...</div>
The same applies to htmlFor, which replaces for on labels.
Self-closing Tags
Every tag must be closed in JSX, including tags that are normally self-closing in HTML.
// Must be closed
<img src="photo.jpg" alt="Photo" />
<input type="text" />
<br />
Single Root Element
A JSX expression must return a single root element. Use the <> Fragment or a <div> as a wrapper.
// Wrong — two root elements
function Example() {
return (
<h1>Title</h1>
<p>Content</p>
);
}
// Correct — use a Fragment
function Example() {
return (
<>
<h1>Title</h1>
<p>Content</p>
</>
);
}
Fragments
A Fragment lets you group elements together without adding an extra DOM node.
import React from 'react';
function List() {
return (
<>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</>
);
}
Summary
JSX makes writing UI easier with HTML-like syntax that is still JavaScript. Understand the small differences such as className, self-closing tags, and the single root element requirement.
The next chapter covers components — how to break UIs into smaller, reusable pieces.