Search⌘ K
AI Features

Example: Building an Expandable Component

Explore how to build an Expandable component using the compound components pattern in React. Learn to manage toggle state with hooks, communicate state via context, and design flexible component APIs. This lesson helps you implement expandable UI elements with clear parent-child state communication.

What is an Expandable Component?

We’ll be building an Expandable component. It will have a clickable header that toggles the display of an associated body of content.

Designing the API

It’s usually a good idea to write out what the exposed API of your component would look like before building it out.

In this case, here’s what we’re going for:

HTML
<Expandable>
<Expandable.Header> Header </Expandable.Header>
<Expandable.Icon/>
<Expandable.Body> This is the content </Expandable.Body>
</Expandable>

In the code block above, you’ll notice I have used expressions like this: Expandable.Header

You can do this as well:

HTML
<Expandable>
<Header> Header </Header>
<Icon/>
<Body> This is the content </Body>
</Expandable>

It doesn’t matter which way as either way works. I have chosen Expandable.Header over Header as a ...