Content Between Tags

The boxes on the festival page all have the same frame: white, with rounded corners and a shadow. The band cards have it, and the tickets should look the same. Instead of writing the same div with the same class everywhere, you can make a component that's just the frame, and put anything into it, as you put text and elements between the tags of a div:

<Card>
    <h3>Camping</h3>
    <p>The campsite opens on Friday.</p>
</Card>

What's between the opening and the closing tag of a component, React passes to it as a prop with a special name: children. The component puts it where it wants it:

export default function Card({ children }) {
    return <div className="card">{children}</div>;
}

So the page gets this:

<div class="card">
    <h3>Camping</h3>
    <p>The campsite opens on Friday.</p>
</div>

children can be anything you can write in JSX: text, elements, other components. And a component can take children together with other props. <Card title="Camping">…</Card> gets both title and children.

Components like this, which just give their content a frame or a layout, are common in React apps: a card, a dialog, a section of a page with a heading. One component decides what the frame looks like, and the rest of the app fills it.

Instructions

In Card.jsx, write a component Card with a default export. It takes the prop children and returns <div className="card">{children}</div>. In App.jsx, import it and replace the div with the class card with <Card>, keeping what's inside.

Give Card a second prop, title, and show it in an <h3> above the children. Then the ticket doesn't need its own heading: write it as <Card title="Friday ticket"> with just the paragraph inside. Add a second ticket the same way: Weekend ticket for €80.

Start programming for free

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

Or sign up with:

Back

7/9

Next