React · Chapter 2 of 26
Props
By the end of this chapter you can give a component its data with props, use one component many times with different props, pass strings, numbers, objects and other values, give a prop a default value, wrap other elements with children, and say why a component never changes its own props. 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
Ira's home page for Diwali week shows every show playing tonight. On Friday 6 November that is 27 showtimes across Parda's twelve venues, and 174 over the week. Chapter 1's ShowCard can show exactly one of them: it imports show.json and reads it, so every ShowCard on the page shows Ghar Wapsi Express at Kala Talkies.
You could copy it: ShowCard2.jsx imports show2.json, ShowCard3.jsx imports show3.json, and so on. That is the by-hand page again. When Datta asks for "seats left" to say "Only 19 left" on a nearly full show, the change goes into every copy, and the one that is forgotten is the next weekend of calls. What you want is one ShowCard that shows whichever show it is given, the way a function works on whatever arguments it is called with. That is what props are.
The lesson
Props are the component's one argument
When you write attributes on your own component's tag, React collects them into one object and passes it to your function. Here is a small tag for a venue, used once in App:
function VenueTag(props) {
console.log('VenueTag got', props);
return (
<p>
{props.name}, {props.area}
</p>
);
}
export default function App() {
return <VenueTag name="Moti Mahal Talkies" area="Camp" seats={460} />;
}
The Preview's console:
VenueTag got {"name":"Moti Mahal Talkies","area":"Camp","seats":460}
That object is the props (short for properties). It is the same object you saw in chapter 1, where lab jsx showed that every tag becomes a call with "an object of its attributes". For an HTML tag like <p>, React uses that object to set the element's attributes. For your own component, React calls your function with it.
Reading props.name everywhere gets long, so React code takes the values out by name, right in the parameter list. This is ordinary JavaScript destructuring:
function VenueTag({ name, area, seats }) {
return (
<p className="venue-tag">
{name}, {area}: {seats} seats
</p>
);
}
{ name, area, seats } means "the argument is an object; give me its name, area and seats as variables". A component always has exactly one parameter, the props object, even when it is destructured.
One component, many uses
Now the same component can show any venue. Venues.jsx uses it three times:
import VenueTag from './VenueTag';
export default function Venues() {
return (
<div className="venues">
<VenueTag name="Moti Mahal Talkies" area="Camp" seats={460} />
<VenueTag name="Natya Ghar" area="Shivajinagar" seats={240} />
<VenueTag name="The Attic" area="Baner" seats={120} />
</div>
);
}
$ lab html Venues.jsx
<div class="venues">
<p class="venue-tag">Moti Mahal Talkies, Camp: 460 seats</p>
<p class="venue-tag">Natya Ghar, Shivajinagar: 240 seats</p>
<p class="venue-tag">The Attic, Baner: 120 seats</p>
</div>
What happens inside: Venues returns a description with three VenueTag elements, each holding its own props object. lab jsx shows them:
$ lab jsx Venues.jsx
...
children: [
_jsx(VenueTag, {
name: "Moti Mahal Talkies",
area: "Camp",
seats: 460
}),
_jsx(VenueTag, {
name: "Natya Ghar",
...
React then calls VenueTag three times, once for each element, with that element's props. With the console.log from the last section, the Preview's console prints three lines, one for each call:
VenueTag got {"name":"Moti Mahal Talkies","area":"Camp","seats":460}
VenueTag got {"name":"Natya Ghar","area":"Shivajinagar","seats":240}
VenueTag got {"name":"The Attic","area":"Baner","seats":120}
One function, three calls, three props objects, three paragraphs. The component is written once; the data changes from use to use.
Strings, numbers and other values
A prop's value is written like any other attribute: text in quotes, anything else in braces. The difference matters, because a value in quotes is always a string:
function Total({ seats, extra }) {
return <p>{seats + extra} seats with the extra chairs</p>;
}
export default function Capacity() {
return (
<>
<Total seats="240" extra="20" />
<Total seats={240} extra={20} />
</>
);
}
$ lab html Capacity.jsx
<p>24020 seats with the extra chairs</p>
<p>260 seats with the extra chairs</p>
"240" + "20" joins two strings; 240 + 20 adds two numbers. Numbers, true and false, objects and arrays all go in braces: seats={460}, soldOut={true}, show={show}, seats={['E7', 'E8']}. Passing a whole object is how you hand a component a show from the data: it gets the object and reads what it needs.
A prop you leave out is simply not in the object, so it is undefined. When the component reads a property of it, that is an error. Here Poster expects a show and App forgot it:
function Poster({ show }) {
return <h2>{show.title}</h2>;
}
export default function App() {
return <Poster />;
}
Your code threw an error
App.jsx, line 2
Cannot read properties of undefined (reading 'title')
When you see "Cannot read properties of undefined", look at the tag that uses the component: the prop is missing, or spelled differently.
Default values
Some props have a sensible value when the parent says nothing. Write it in the destructuring, with =, as JavaScript allows for any parameter:
function HoldNote({ minutes = 10 }) {
return <p>Seats are held for {minutes} minutes.</p>;
}
export default function Notes() {
return (
<>
<HoldNote />
<HoldNote minutes={15} />
<HoldNote minutes={0} />
<HoldNote minutes={null} />
</>
);
}
$ lab html HoldNote.jsx
<p>Seats are held for 10 minutes.</p>
<p>Seats are held for 15 minutes.</p>
<p>Seats are held for 0 minutes.</p>
<p>Seats are held for minutes.</p>
The default is used only when the prop is undefined, that is, when it is left out. 0 is a real value and stays 0. null is a value too: it is kept, and React shows nothing for it.
children: what goes between the tags
So far every component closed itself, <VenueTag ... />. A component can also be written with an opening and a closing tag and something between them, like an HTML element. Whatever is between the tags reaches the component as one more prop, called children:
function Badge({ children }) {
return <span className="badge">{children}</span>;
}
export default function Badges() {
return (
<p>
<Badge>Sold out</Badge>
<Badge>
<strong>4.7</strong> rated
</Badge>
</p>
);
}
$ lab html Badge.jsx
<p>
<span class="badge">Sold out</span>
<span class="badge">
<strong>4.7</strong>
rated
</span>
</p>
lab jsx shows that children is just a key in the props object, like any other:
$ lab jsx Badge.jsx
...
export default function Badges() {
return _jsxs("p", { children: [_jsx(Badge, { children: "Sold out" }), _jsxs(Badge, { children: [_jsx("strong", { children: "4.7" }), " rated"] })] });
}
The first Badge's children is a string; the second's is an array of an element and a string. Badge does not care: it puts {children} where it wants it. Components like this are wrappers: they draw a frame, a card or a layout, and the parent decides what goes inside.
Props are read-only
Props belong to the parent that wrote them. A component that changes them is changing someone else's data, so React does not allow it. In development it freezes every props object; Object.isFrozen(props) inside a component prints frozen? true in the Preview's console. Try to assign to one:
function SeatsLeft(props) {
props.seats = props.seats - props.booked;
return <p>{props.seats} seats left</p>;
}
export default function App() {
return <SeatsLeft seats={460} booked={277} />;
}
Your code threw an error
App.jsx, line 2
Cannot assign to read only property 'seats' of object '#<Object>'
The fix is to leave the props alone and work out what you need in a variable of the component's own: const left = seats - booked; and the page says 183 seats left.
React freezes only the props object itself, not the objects inside it. Changing a show you were given does not throw, and that is worse:
const show = { title: 'Lal Batti', venue: 'Chitra Mandir' };
function LoudTitle({ show }) {
show.title = show.title.toUpperCase();
return <h2>{show.title}</h2>;
}
function Venue({ show }) {
return (
<p>
{show.title} at {show.venue}
</p>
);
}
With <LoudTitle show={show} /> and then <Venue show={show} />, the Preview shows:
LAL BATTI
LAL BATTI at Chitra Mandir
Venue never asked for capitals: LoudTitle changed the object the two share. This is the rule behind it all: data flows one way, down. A parent passes values to its children as props; a child reads them and never writes them. When a child needs something changed, it asks its parent, which is chapter 5's events, and the parent passes the new value down.
Spreading an object as props
When an object's keys are exactly the props a component wants, you can spread it onto the tag instead of writing each one:
import VenueTag from './VenueTag';
const venue = { name: 'Sur Sangam Hall', area: 'Deccan', seats: 280 };
export default function Spread() {
return <VenueTag {...venue} />;
}
lab html prints <p class="venue-tag">Sur Sangam Hall, Deccan: 280 seats</p>, and lab jsx shows _jsx(VenueTag, { ...venue }): a copy of the object becomes the props. It saves typing, but it also hides which props a component really gets, so most of this lab passes them by name.
Your turn
Four tasks, one file each. Task 1 makes ShowCard show the show in its show prop; App.jsx already uses it three times, and the Check gives it other shows too. Task 2 is Panel, a wrapper with a title over whatever is inside it. Task 3 is Price, whose fee is 20 when none is given: the trap is the member's fee of 0, which is a real fee. Task 4 is an interview question: Datta's OfferPrice throws as soon as it renders. Fix it without touching its props, show it in App.jsx, and be ready for Rukhsana's question: why can a component not change its props, and which way does data flow? Watch the Preview as you save, open its console when something looks wrong, 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
ShowCard.jsx: a card for any show
App.jsx shows three of tonight's shows with one component: <ShowCard show={shows[0]} /> and two more like it. Keep the line export default function ShowCard({ show }) and make ShowCard return an <article> that shows, from the show in its show prop, a heading h2 with the title, then five paragraphs. For shows[0] that is exactly:
Ghar Wapsi Express (the h2)
Kala Talkies, Sadashiv Peth
Fri 6 Nov, 9:30 pm
Hindi, UA 13+
From ₹120
27 seats left
The lines are the venue and the area; the day and the time; the language and the certificate; From ₹ and the lowest price (priceFrom); and the seats minus the booked seats (412 minus 385). Every value comes from the show prop, never typed in and never from shows.json: the Check gives the card other shows, such as The Tiffin Thief at Rangdeep Studio Theatre, Erandwane, on Sat 7 Nov at 4:00 pm, English, certificate U, from ₹250, with 82 of its 180 seats booked; then it must say English, U and 98 seats left. Give the <article> className="show-card" for app.css; the Check does not look at classes.
- Task 2
Panel.jsx: a panel that wraps what is inside it
App.jsx uses Panel with an opening and a closing tag and other elements between them: <Panel title="Your basket"> ... </Panel>. Keep the line export default function Panel({ title, children }) and make Panel return a <section> that holds, in this order, a heading h2 with the title prop, then everything between the tags, which React passes to Panel as its children prop. Give the <section> className="panel" for app.css; the Check does not look at classes.
Panel must not know what it holds: the Check puts other things inside it, first two paragraphs (with the title Before you book) and then a list (with the title Getting there), and they must appear inside the section, after the h2.
- Task 3
Price.jsx: a price with a default fee
Price gets three props: seats (how many seats), price (rupees for one seat) and fee (Parda's booking fee, rupees for one seat). When no fee is given, fee is 20. Make Price return a paragraph, with className="price" for app.css, that says exactly, for seats={2} and price={180} with no fee:
2 seats at ₹180 + ₹40 fee = ₹400
That is the seats, the price of one seat, the fee for all the seats (2 times 20) and the total (360 plus 40). A fee of 0 is a real fee: members pay no fee, so App.jsx passes fee={0}, and seats={4} price={120} fee={0} must say 4 seats at ₹120 + ₹0 fee = ₹480. The Check also tries seats={3} price={250} fee={30}, which must say 3 seats at ₹250 + ₹90 fee = ₹840.
- Task 4 · interview question
Interview: OfferPrice.jsx, the price that changed its props
Datta's OfferPrice takes rupees off a seat's price for Diwali week. It gets two props, price (rupees for one seat) and off (rupees taken off), and for price={180} off={30} it must show a paragraph that says exactly ₹150 in Diwali week, was ₹180. It throws an error as soon as it renders instead. Fix it without changing anything in its props: the Check also tries price={250} off={50}, which must say ₹200 in Diwali week, was ₹250. Keep className="offer" for app.css. When it works, remove the {/* */} around <OfferPrice price={180} off={30} /> in App.jsx to see it in the Preview (the Check shows OfferPrice on its own).
Rukhsana will ask: why can a component not change its own props, and which way does data flow between components?
What you will learn
- Props: the one argument React passes a component, an object of the attributes you wrote on its tag.
- Destructuring props: taking the values out by name, in the parameter list.
- Values in props: text in quotes; numbers, objects, arrays and anything else in braces.
- Default values: what a prop is when the parent leaves it out.
- children: what you put between a component's opening and closing tags.
- Props are read-only: React freezes them, and data flows one way, down.
More in Thinking in components
Build "Props" 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.