What you'll learn
What JSX is, how to embed JavaScript values in it, and the few rules that differ from HTML.
Why it matters
JSX is how you describe what a React screen looks like. Every React component you ever read or write uses it.
Explanation
React is a JavaScript library for building user interfaces out of small, reusable pieces. You describe what the screen should look like, and React keeps the page up to date.
JSX looks like HTML written inside JavaScript. Behind the scenes it is converted to plain JavaScript function calls.
const element = <h1>Hello, world</h1>;Rules to remember:
- One parent: a component returns a single root element. Wrap siblings in a
<div>or a fragment<>...</>. - Curly braces
{ }insert any JavaScript expression:{name},{2 + 3},{user.age}. classNameinstead ofclass, becauseclassis a reserved word in JavaScript.- Close every tag, including
<img />and<input />.
Example
function App() {
const name = "Asha";
const items = 3;
return (
<div>
<h1 className="title">Hello, {name}!</h1>
<p>You have {items} items, worth {items * 20} rupees.</p>
</div>
);
}Step-by-step walkthrough
Appis a function that returns JSX. React calls it to know what to draw.{name}is replaced byAshain the heading.{items * 20}is calculated before it is shown:60.classNamesets the CSS class. It becomesclassin the actual HTML.- Everything sits inside one
<div>, the single parent.
Try it yourself
Change the name, add a second paragraph, and show today's year with {new Date().getFullYear()}.
JSXReact
Common mistakes
- Using
classinstead ofclassName. - Returning two siblings without a wrapper.
- Forgetting to close tags like
<img>. - Putting statements in braces. Only expressions work. Use a ternary instead of
if.
Quick quiz
Summary
- JSX describes UI inside JavaScript.
{ }inserts expressions; useclassName; close every tag; one root element.- A component is a function that returns JSX.
Next: components.