A List of Cards

map() can turn data into components too, not just into lis. In the Props lesson, you wrote one BandCard for each band. With five bands, that's five lines; with fifty bands, it'd be fifty, and each new band in the data would need one more. One map() shows them all:

{bands.map((band) => (
    <BandCard key={band.id} band={band} />
))}

For each band, map() returns a BandCard and gives it the band in its props. The key goes on the element that map() returns: here, on the BandCard. It's the cards that are the items of the list, not the articles inside them.

The data is now in a file of its own, bands.js. It's a plain JavaScript file, without JSX, that exports the array: export const bands = [ … ];. App.jsx imports it with a named import, as you know from the Components lesson: import { bands } from "./bands.js";. With the data in its own file, the components stay short, and several components can import the same data.

Typical mistakes:

  • The key inside BandCard, on its article. React needs the key on the items of the list, and in BandCard, there's no list, just one article. The console keeps warning.
  • Reading the key in BandCard. key isn't one of the props, so function BandCard({ key }) gets undefined, and the console warns that key is not a prop. When the card needs the id, it has band.id.

Instructions

Replace the two BandCards with one map() that shows a card for each band in bands.

Give each card a key, so that the console has no warning.

Start programming for free

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

Or sign up with:

Back

3/11

Next