JSX
Write HTML-like markup right inside JavaScript. JSX is what makes React so readable.
What you will learn
- Write JSX markup
- Embed JavaScript expressions with { }
- Follow the JSX rules
HTML inside JavaScript
JSX lets you write HTML-like markup inside JavaScript. The browser cannot read it directly — a tool (Babel/Vite) converts it to real JavaScript behind the scenes.
Curly braces embed JavaScript
Anything inside { } in JSX is live JavaScript — variables, calculations, function calls.
function App() {
const name = "Asha";
const year = 2026;
return (
<div>
<h2>Hello, {name}!</h2>
<p>Next year is {year + 1}.</p>
<p>2 + 2 = {2 + 2}</p>
</div>
);
}Everywhere you see { }, React runs the JavaScript inside and drops the result into the page. {name} prints the value of the name variable ("Asha"). {year + 1} actually does the maths and prints 2027. {2 + 2} prints 4. The text outside the braces is plain HTML; the braces are the doorway to JavaScript.
Note: Output:
Hello, Asha!
Next year is 2027.
2 + 2 = 4
Notice React calculated year + 1 and 2 + 2 for you — anything inside { } is live code, not just text.
The JSX rules
- Return one root element (wrap siblings in a
<div>or<>...</>fragment). - Use
classNameinstead ofclass(becauseclassis a JS keyword). - Close every tag, including
<img />and<br />. - Use
{ }for any dynamic value.
Watch out: In JSX, write className, not class. And every component must return a single root element — wrap multiple elements in a <div> or an empty <>...</> fragment.
This example shows the fragment rule in action — two elements returned as one, using an empty <>...</> wrapper:
function App() {
return (
<>
<h3 className="title">Using a fragment</h3>
<p>These two elements share one root: an empty <> fragment.</p>
</>
);
}A component can only return one element. Here the <h3> and <p> are two siblings, so we wrap them in an empty <>...</> — a fragment. It groups them under one root without adding an extra <div> to the page. Also notice className="title" instead of class — that is the JSX way to set a CSS class.
Note: Output: A heading Using a fragment followed by the line “These two elements share one root: an empty <> fragment.” — both rendered, with no wrapper div added around them in the final HTML.
Q. In JSX, how do you add a CSS class to an element?
✍️ Practice
- Embed a variable and a calculation in JSX using
{ }. - Return two elements wrapped in a fragment
<>...</>.
🏠 Homework
- Create a component that shows your name, age and a calculation, all via JSX expressions.