React JSX
JSX is a syntax extension for JavaScript that lets you write HTML-like markup directly inside your component functions.
What Is JSX?
JSX stands for JavaScript XML. It looks like HTML, but it's actually syntactic sugar for calling functions that create React elements. A build tool such as Vite or Babel compiles JSX into plain JavaScript before it reaches the browser.
JSX Compiles to Function Calls
function Label() {
// Writing this JSX:
return <span className="tag">New</span>;
}
// is roughly equivalent to writing:
// React.createElement('span', { className: 'tag' }, 'New')
export default Label;Embedding JavaScript Expressions
Curly braces {} let you drop any JavaScript expression into your markup, including variables, function calls, arithmetic, and ternaries. Statements like if or for are not allowed directly inside braces, but expressions are.
Expressions Inside JSX
function OrderSummary() {
const itemCount = 3;
const pricePerItem = 12.5;
const total = itemCount * pricePerItem;
return (
<p>
You have {itemCount} items totaling ${total.toFixed(2)}
{itemCount > 2 ? ' (bulk discount applied)' : ''}
</p>
);
}
export default OrderSummary;JSX Rules to Remember
JSX looks like HTML but follows JavaScript rules underneath, which leads to a few important differences from regular HTML.
- A component must return a single root element, or use a fragment <>...</> to group siblings.
- Attributes use camelCase, such as className instead of class and onClick instead of onclick.
- Every tag must be closed, including void elements like <img /> and <br />.
- JavaScript reserved words are renamed: use htmlFor instead of for on labels.
- Comments inside JSX use the {/* comment */} syntax.
Fragments Avoid Extra Wrapper Divs
function UserInfo() {
return (
<>
<h2>Jane Doe</h2>
<p>jane@example.com</p>
</>
);
}
export default UserInfo;Conditional Rendering and Lists
Because JSX is just JavaScript, you can use standard operators like && and .map() to conditionally show markup or render collections, which is essential for realistic UIs.
Conditional Rendering and .map()
function Notifications({ messages }) {
return (
<div>
{messages.length === 0 && <p>No new notifications.</p>}
<ul>
{messages.map((msg) => (
<li key={msg.id}>{msg.text}</li>
))}
</ul>
</div>
);
}
function App() {
const messages = [
{ id: 1, text: 'Your order has shipped.' },
{ id: 2, text: 'New comment on your post.' },
];
return <Notifications messages={messages} />;
}
export default App;Exercise: React JSX
What is JSX?