React · Chapter 1 of 26
React, and your first components
By the end of this chapter you can say why Parda builds its new site with React, write a component (a function that returns JSX), put values in JSX with { }, follow JSX's rules (one parent, every tag closed, className and htmlFor), read what JSX compiles to, start an app with createRoot in main.jsx, and use the Preview and its console to see your app and its mistakes. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Thinking in components
- 4 tasks
- React
- Free chapter
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.
Why you need this
Parda sells tickets for twelve of Pune's own venues: single-screen cinemas like Kala Talkies in Sadashiv Peth and Moti Mahal Talkies in Camp, small theatres like Rangdeep and Natya Ghar, a comedy club in Baner and an open-air lawn in Aundh. Its web pages are full of things that change while you look at them: seats left on a show, the seats you have picked, the total on the Pay button, a show that sells out.
Parda's booking page today is about 1,900 lines of JavaScript that change the page by hand: find an element, set its text, find the next one. Every time something changes, the code has to remember every place on the page that shows it. On Friday 16 October, the opening night of Ghar Wapsi Express at Kala Talkies, the code that removes a seat from your basket forgot one of those places: the Pay button kept the old total. Datta, who runs support and the box office, took 140 calls that weekend, and 61 people were refunded for a seat they had removed. Sayali, the founder, wants a new site before Diwali week, which starts on Friday 6 November.
Here is that bug, small enough to read. A basket of two seats, made with the DOM, and the function that removes a seat:
const basket = { seats: ['E7', 'E8'], price: 180 };
function renderBasket() {
const box = document.createElement('aside');
const title = document.createElement('h2');
title.textContent = 'Your seats';
const seats = document.createElement('p');
seats.className = 'seats';
seats.textContent = basket.seats.join(', ');
const pay = document.createElement('button');
pay.className = 'pay';
pay.textContent = `Pay ₹${basket.seats.length * basket.price}`;
box.append(title, seats, pay);
document.getElementById('basket').append(box);
}
// Called when someone removes a seat: change every place that shows it.
function removeSeat(seat) {
basket.seats = basket.seats.filter((s) => s !== seat);
document.querySelector('.seats').textContent = basket.seats.join(', ');
}
The page's HTML before and after removeSeat('E8'), printed by Node in the lab:
<aside><h2>Your seats</h2><p class="seats">E7, E8</p><button class="pay">Pay ₹360</button></aside>
<aside><h2>Your seats</h2><p class="seats">E7</p><button class="pay">Pay ₹360</button></aside>
One seat, and the button still asks for ₹360. Nothing is wrong with any single line: the code simply has to know, in every function that changes something, every place that shows it. With 23 such places on the booking page, someone forgets one. Rukhsana, Parda's senior frontend engineer, is rebuilding the site with React, and you build it with her. Ira, the designer, has drawn every page. You know JavaScript; you have not written React before, and this lab starts there.
The lesson
Describe it once, for any data
Here is the same basket in React:
import basket from './basket.json';
export default function Basket() {
const total = basket.seats.length * basket.price;
return (
<aside>
<h2>Your seats</h2>
<p>{basket.seats.join(', ')}</p>
<button>Pay ₹{total}</button>
</aside>
);
}
There is no "find the button and change it". The function says what the basket looks like for whatever the data is, and the total is worked out in one place. When the data changes, React calls the function again, compares what it returns with what it returned last time, and changes the page only where they differ. We removed E8 and asked React to show the basket again; the page's HTML before and after:
<aside><h2>Your seats</h2><p>E7, E8</p><button>Pay ₹360</button></aside>
<aside><h2>Your seats</h2><p>E7</p><button>Pay ₹180</button></aside>
React kept all four elements and made exactly two changes: the text E7, E8 became E7, and 360 became 180. A forgotten place cannot happen, because there is no list of places to remember. (How the data changes while the page is open is chapter 7's useState; for now each component shows data that is already there.)
A component is a function
A component is a JavaScript function that returns a piece of the page. Here is Parda's list of cinemas:
export default function Cinemas() {
return (
<ul className="cinemas">
<li>Kala Talkies</li>
<li>Nilambari Cinema</li>
<li>Moti Mahal Talkies</li>
</ul>
);
}
- Its name starts with a capital letter. That is how React tells your component
<Cinemas />apart from an HTML tag like<ul>. - It is exported, so another file can import it and use it as a tag:
<Cinemas />. - What it returns is JSX: tags written inside JavaScript. The round brackets only let the JSX start on the next line.
The lab's terminal can show what a component puts on the page:
$ lab html Cinemas.jsx
<ul class="cinemas">
<li>Kala Talkies</li>
<li>Nilambari Cinema</li>
<li>Moti Mahal Talkies</li>
</ul>
A whole page is components inside components. In this chapter's App.jsx, App returns <Header />, <SearchBar /> and <ShowCard /> inside a <main>, so the page is a tree: App at the top, your components inside it, and HTML elements at the leaves. Every component you write this lab is one piece of that tree.
JSX is JavaScript
The browser does not understand JSX. Before your code runs, a compiler turns every tag into a call to a function from React. lab jsx shows what the Basket above becomes:
$ lab jsx Basket.jsx
import basket from "./basket.json";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
export default function Basket() {
const total = basket.seats.length * basket.price;
return _jsxs("aside", { children: [
_jsx("h2", { children: "Your seats" }),
_jsx("p", { children: basket.seats.join(", ") }),
_jsxs("button", { children: ["Pay ₹", total] })
] });
}
Each tag is one call: its name, then an object of its attributes and children. What a call returns is a plain object, a React element, that describes what to show. Printed with Node:
{
'$$typeof': Symbol(react.transitional.element),
type: 'button',
key: null,
props: { children: [ 'Pay ₹', 360 ] },
_owner: null,
_store: {}
}
Your component does not touch the page at all: it returns a description, and React builds or changes the real elements from it. Three rules of JSX come straight from this.
Values go in { }. Inside the braces is any JavaScript expression: a variable, a sum, a method call. Text outside braces is shown as it is.
const venue = { name: 'Moti Mahal Talkies', area: 'Camp', opened: 1946 };
export default function VenueAge() {
return (
<p>
{venue.name} in {venue.area} has been open for {2026 - venue.opened} years
</p>
);
}
$ lab html VenueAge.jsx
<p>Moti Mahal Talkies in Camp has been open for 80 years</p>
Only expressions fit in the braces, because they become values in an object: an if or a for cannot, which is why chapter 3 lists things with map and chapter 4 chooses with ? :.
One parent. A function returns one value, so a component returns one element. Two tags side by side would be two calls with nothing joining them. Wrap them in one parent element, or in a fragment, <> and </>, which groups them without adding an element to the page.
Every tag closes, and attributes have JavaScript's names. The compiler must know where each call ends, so a tag with nothing inside closes itself: <br />, <hr />, <input />. Attributes become keys of an object, so they are written the way the browser's JavaScript names them: class and for are words JavaScript keeps for itself, and JSX writes className and htmlFor. A text value goes in quotes, any other value in braces:
<a className="help" href="mailto:help@parda.example">Write to us</a>
<button type="button" disabled={true}>Sold out</button>
When JSX goes wrong
Three mistakes everyone makes in their first week, with what you really see. Two tags without a parent stop the compiler, and the Preview shows the file and the line:
Your code does not compile
Notice.jsx, line 34
Adjacent JSX elements must be wrapped in an enclosing tag
A tag that never closes stops it too. The Check says:
Notice.jsx does not compile: line 28: Expected corresponding JSX closing tag for 'hr'
The Check notices only at line 28, where the parent closes and finds the <hr> still open. The Preview points at the open tag itself:
Your code does not compile
Notice.jsx, line 26
<hr> is not closed. In JSX every tag closes: write <hr /> (or <hr></hr>).
HTML's class and for do compile, but React warns, in the Preview's console:
Invalid DOM property `class`. Did you mean `className`?
Invalid DOM property `for`. Did you mean `htmlFor`?
And a component used with a small first letter is taken for an HTML tag the browser has never heard of:
<showCard /> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.
The tag <showCard> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.
Read the first message, go to its file and line, fix it, and save. The Check fails on any of React's warnings, as a code review would.
main.jsx and createRoot
Every app starts in one file. This chapter's is main.jsx:
import { createRoot } from 'react-dom/client';
import App from './App';
import './app.css';
const root = createRoot(document.getElementById('root'));
root.render(<App />);
- The page starts with one empty element,
<div id="root"></div>. - createRoot (from react-dom, React's part that knows the browser) makes that element a root: from now on React manages what is inside it.
- root.render(\<App /\>) asks React to show App there. React calls App, then every component App uses, and builds the elements they describe inside
#root. import './app.css'adds Ira's styles to the page. A rule like.show-card { ... }styles the element whoseclassNameisshow-card.
You will rarely change main.jsx: everything else happens inside App.
The Preview
The Preview beside the editor runs your app the way a browser runs a real site: it takes your saved files, compiles each one, runs main.jsx, and shows the page. Save a file and it runs again. Under it is the app's console, where console.log prints, and where React's warnings and your errors appear. A compile error or an error thrown while rendering covers the page with the file, the line and the message.
The starter files already show something: each component returns a line that says which task goes there, and App puts them in their places. As you finish each task, its line turns into Parda's page.
The Check is separate: it runs hidden tests on your saved files in the lab, shows each component on its own in a browser-like page, and reads it the way a person would, by its headings, labels, buttons and text. It never looks at your class names. When a task fails, the first line of its message says what it saw and what the task asks for.
Your turn
Four tasks, one file each, at the top. Task 1 is Parda's header, a <header> with the name and one line under it. Task 2 is tonight's show card from show.json, every value in { }: the Check also shows your card with another show, so nothing can be typed in. Task 3 is the search box, where class and for would make React warn. Task 4 is an interview question: Datta's notice does not compile; fix it, then show it in App.jsx, and be ready for Rukhsana's question: what does JSX compile to, and why one parent? Watch the Preview as you save, and press Check when a task looks right.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
Header.jsx: Parda's header
Make the Header component in Header.jsx return a <header> element that holds exactly these two, in this order: a main heading, an h1, that says Parda, and a paragraph, a p, that says Tickets for Pune's own cinemas and stages.
Keep the line export default function Header() as it is: App.jsx imports Header by its default export, and a component's name starts with a capital letter. Letters and spaces must match exactly. Give the <header> className="site-header" so that app.css styles it in the Preview; the Check does not look at classes.
- Task 2
ShowCard.jsx: tonight's show card
Tonight's show is in show.json, which ShowCard.jsx imports as show. Make ShowCard return an <article> that shows, from show's values, a heading h2 with the title, then five paragraphs, exactly:
Ghar Wapsi Express (the h2)
Kala Talkies, Sadashiv Peth
Fri 6 Nov, 9:30 pm
Hindi, 2 h 22 min
From ₹120
27 seats left
2 h 22 min is show.minutes (142) as whole hours and the minutes left over; seats left is show.seats minus show.booked (412 minus 385). Every value comes from show, inside { }, never typed in: the Check also shows the card with another show in show.json, The Tiffin Thief at Rangdeep Studio Theatre, Erandwane, on Sat 7 Nov at 4:00 pm, in English, 95 minutes long, from ₹250, with 82 of its 180 seats booked. Then the card must say English, 1 h 35 min and 98 seats left. Give the <article> className="show-card" for app.css; the Check does not look at classes.
- Task 3
SearchBar.jsx: the search box
Make SearchBar return a <form> that holds, in this order: a <label> that says Search shows; an <input> with type search, the id show-search and the placeholder Film, play or artist; and a <button> that says Search. The label must belong to the input, so give the label htmlFor="show-search", the input's id. Give the form className="search" for app.css; the Check does not look at classes. Searching does nothing yet: it starts working in chapter 9.
JSX writes className and htmlFor where HTML writes class and for, because class and for are words JavaScript keeps for itself. React warns about class and for, and the Check fails on any of React's warnings. Every tag must close, so the input ends with />.
- Task 4 · interview question
Interview: Notice.jsx, the notice that will not compile
Datta's notice in Notice.jsx does not compile. Fix it, so that it shows exactly: a heading h2 that says Before you book; a paragraph that says Seats are held for 10 minutes while you pay.; a line, the <hr>, between the two paragraphs; and a paragraph that says Questions? Write to help@parda.example.
Keep the line const holdMinutes = 10; as it is: the Check also changes it to const holdMinutes = 15;, and then the first paragraph must say Seats are held for 15 minutes while you pay. When Notice.jsx compiles, remove the // before Notice's import in App.jsx and the {/* */} around <Notice /> to see it in the Preview (the Check shows Notice on its own).
Rukhsana will ask: what does the JSX in a component compile to, and why must a component return one parent element?
What you will learn
- Why React: you describe what the page looks like for the data, and React changes the page to match.
- Components: functions that return a piece of the page, used like tags.
- JSX: tags inside JavaScript, { } for values, and what it compiles to.
- JSX's rules: one parent, every tag closed, className and htmlFor.
- main.jsx and createRoot: how the app gets onto the page.
- The Preview: your app beside the editor, its console, and its errors.
More in Thinking in components
Build "React, and your first components" yourself
Parda sells tickets for Pune's own cinemas and stages, and its booking page broke on opening night. You rebuild it in React. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.