Summary

In this lesson, you learned that:

  • map() turns an array of data into an array of elements, and React shows an array in curly braces element by element: {bands.map((band) => <li key={band.id}>{band.name}</li>)}. It works for components too: <BandCard key={band.id} band={band} />.
  • Each item of a list needs a key, unique in the list and the same for the same item, so that React can tell the items apart when the list changes. Take it from the data (band.id), not from the position in the array. It goes on the element that map() returns, and the component doesn't get it in its props. Without keys, the console warns: Each child in a list should have a unique "key" prop.
  • What a list shows is decided before return: filter() picks some of the items, sort() puts them in another order. sort() changes the array itself, so sort a copy: [...bands].sort(…). A component doesn't change the data it gets.
  • if can't go in curly braces, but it can go before return. An early return deals with a special case first: if (bands.length === 0) { return <p>No bands yet.</p>; }. A component that has nothing to show returns null.
  • The conditional operator condition ? a : b gives a when the condition is true and b when it isn't. It's an expression, so it can go in JSX: for a text, an element or an attribute (className={band.day === "Friday" ? "card friday" : "card saturday"}).
  • condition && element gives the element or nothing: for false, true, null and undefined, React shows nothing. But it does show numbers, and 0 && … gives 0, so compare: likes > 0 && ….

In the next lesson, Checkpoint: Recipe Book, you'll put components, props, lists and conditions together in an app of your own: a recipe book.

But first, a little practice: the festival's list of tickets. The tickets are in App.jsx, and the rest is up to you.

Instructions

Under the heading, show the tickets in a list ul: for each ticket, an li that says its name and price, as in Friday: €45. Don't forget the keys.

A ticket with nothing left is sold out. Instead of its price, its item says Sold out (Saturday: Sold out), and it has the class sold-out, which grays it out.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

11/11

Next