Destructuring Props

Writing props. in front of every prop gets long once a component has more of them. That's why React code usually takes the props out of the object right in the parameters, with destructuring, which you know from the JavaScript course:

const { name, stage } = band;

In the parameters, it's the same, just without const and =. The curly braces take the props out of the object that React passes:

export default function BandCard({ name, stage }) {
    return (
        <article className="card">
            <h3>{name}</h3>
            <p>{stage}</p>
        </article>
    );
}

The component works just as before, but it's shorter, and its first line tells you which props it takes. That's how components are written in most React code, and in the rest of this course too.

Typical mistakes:

  • Forgetting the curly braces: function BandCard(name, stage). React passes one object, so name is that whole object, with all the props in it. React can't show an object, so the page is empty, and the console says Objects are not valid as a React child (found: object with keys {name, stage}).
  • Still writing props.name after destructuring. There's no props any more, only name, so the console says ReferenceError: props is not defined.

Instructions

Change BandCard so that it destructures its props in the parameters, { name, stage }, and shows {name} and {stage} without props. in front. The cards look the same as before.

Add a third prop, time, when the band plays: 20:00, 18:30 and 16:00. Add it to the destructuring and show it in the paragraph after the stage, with a comma between them: Main Stage, 20:00.

Start programming for free

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

Or sign up with:

Back

2/9

Next