JSX
JSX lets you write HTML-like markup inside JavaScript. It looks like HTML but compiles to JavaScript function calls.
React (JSX)
function App() {
const name = "Asha";
return <h1>Hello, {name}!</h1>;
}JavaScript in braces
Anything inside { } is a JavaScript expression:
React (JSX)
function App() {
const price = 250;
const qty = 3;
const user = { first: "Leo", last: "Kim" };
return (
<div>
<p>Total: {price * qty}</p>
<p>Customer: {user.first + " " + user.last}</p>
<p>Shouting: {"react".toUpperCase()}</p>
<p>Today: {new Date().toDateString()}</p>
</div>
);
}Expressions only: no if statements or for loops directly inside braces (the conditional rendering and lists lessons show the patterns that replace them).
The rules of JSX
1. Return one parent element. Wrap siblings in a <div> or an empty fragment <>...</>:
React (JSX)
function App() {
return (
<>
<h2>Title</h2>
<p>Two elements, one fragment around them.</p>
</>
);
}2. className instead of class, because class is a JavaScript keyword:
React (JSX)
function App() {
return (
<div>
<style>{`.badge { background: #5a48f5; color: white; padding: 4px 10px; border-radius: 999px; }`}</style>
<span className="badge">New</span>
</div>
);
}3. Close every tag, including ones HTML leaves open: <img />, <br />, <input />.
4. camelCase attributes: onClick, tabIndex, htmlFor (instead of for).
5. style takes an object, with camelCase property names:
React (JSX)
function App() {
const box = { backgroundColor: "#e6f9ff", padding: 16, borderRadius: 12, fontSize: 18 };
return <div style={box}>Styled with an object</div>;
}Numbers like padding: 16 mean pixels.
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.