Objects and Arrays
Apps rarely write their data straight into JSX. The data is usually in an array of objects, loaded from a server or kept in a file, like the festival's bands at the top of App.jsx:
const bands = [
{ id: 1, name: "Night Trains", stage: "Main Stage", day: "Friday", time: "20:00", genre: "rock" },
{ id: 2, name: "Lunar Cats", stage: "Tent", day: "Friday", time: "18:30", genre: "pop" },
// …
];Props can be values from the array: name={bands[0].name}. But with more fields, every card gets long. A prop can be any value, a whole object too, so you can pass the band as a single prop:
<BandCard band={bands[0]} />The card then takes the prop band and reads the band's properties:
export default function BandCard({ band }) {
return (
<article className="card">
<h3>{band.name}</h3>
<p>{band.genre}</p>
</article>
);
}Which way is better? Separate props such as name and stage show at once what the component needs, and they work with any data, even text written straight into JSX. A single object is shorter when the data already is an object and the component needs most of its fields. You'll see both in React code.
An array can be a prop, too. A component with a list of stages, for example, can show them separated by commas, with join():
<StageList stages={["Main Stage", "Tent", "Forest Stage"]} />export default function StageList({ stages }) {
return <p>Stages: {stages.join(", ")}</p>;
}Stages: Main Stage, Tent, Forest StageWriting bands[0], bands[1] and so on for every card is tedious, and when a band is added, you have to add a line. The next lesson shows how to make a card for every element of an array. For now, write the cards one by one.
Instructions
Change BandCard so that it takes a single prop, band, and reads band.name, band.stage and band.time. In App.jsx, pass each card its band: <BandCard band={bands[0]} /> and so on. The cards look the same as before.
Add cards for the other two bands, bands[3] and bands[4], so that the lineup shows all five.
Now an array as a prop. Give Header the prop days with the array ["Friday", "Saturday"]. Header shows the days below the heading, in a paragraph: <p>{days.join(" and ")}</p>. The page shows Friday and Saturday.