← All Articles
ReactAug 2, 2024◷ 4 min read

Building Reusable UI with Compound Components

Introduction

In UI development, creating components that are both reusable and flexible can be challenging. Traditional component designs often become cumbersome as requirements evolve, leading to rigid and difficult-to-maintain code. The Compound Component pattern addresses these issues by allowing you to break down complex components into smaller, more manageable parts. This pattern not only enhances reusability but also provides fine-grained control over component behavior and styling.

In this post, I'll explain the compound component pattern using two examples:

text
Accordion
and
text
Card
components. We will cover the key steps in implementing this pattern, including the use of context to manage shared state and the reasons for splitting components into subcomponents.

Why Use the Compound Component Pattern?

Benefits of Compound Components

  • Flexibility: Allows developers to compose and control components in various ways, providing greater customization options.
  • Reusability: Subcomponents can be reused independently or together, enhancing modularity.
  • Maintainability: Smaller, focused components are easier to maintain and extend.

Why Context is Needed

Context in React is a way to pass data through the component tree without having to pass props down manually at every level. In the compound component pattern, context is used to manage shared state and communication between subcomponents. This is particularly useful when dealing with components that need to coordinate their state or behavior, such as an

text
Accordion
where multiple items need to know which one is open.

Steps to Implement Compound Components

Step 1: Define the Context

First, we create a context to manage the shared state. This is necessary when multiple subcomponents need to interact with the same piece of state, such as the currently open item in an

text
Accordion
.

Example: Accordion Context

js
import { createContext, useContext, useState } from 'react';

const AccordionContext = createContext();

Here,

text
AccordionContext
will be used to provide and consume state related to which accordion item is open.

Step 2: Create the Parent Component

The parent component (e.g.,

text
Accordion
) is responsible for managing the shared state and providing it to its children via context.

Example: Accordion Component

jsx
1const Accordion = ({ children }) => {
2  const [openIndex, setOpenIndex] = useState(null);
3
4  return (
5    <AccordionContext.Provider value={{ openIndex, setOpenIndex }}>
6      <div className="accordion">{children}</div>
7    </AccordionContext.Provider>
8  );
9};

In this example, the

text
Accordion
component holds the state for which item is open and provides this state to its children through
text
AccordionContext
.

Step 3: Create Subcomponents

Next, we create subcomponents that will use the context to coordinate their behavior. These subcomponents are designed to be composable and independent of each other.

Example: Accordion Subcomponents

jsx
1const AccordionItem = ({ children, index }) => {
2  const { openIndex, setOpenIndex } = useContext(AccordionContext);
3  const isOpen = openIndex === index;
4
5  return (
6    <div className="accordion-item">
7      {children({ isOpen, toggle: () => setOpenIndex(isOpen ? null : index) })}
8    </div>
9  );
10};
11
12const AccordionTrigger = ({ children, toggle }) => (
13  <button className="accordion-trigger" onClick={toggle}>
14    {children}
15  </button>
16);
17
18const AccordionContent = ({ children, isOpen }) => (
19  <div className={`accordion-content ${isOpen ? 'open' : ''}`}>{children}</div>
20);

In these subcomponents:

  • text
    AccordionItem
    uses the context to determine if it should be open and provides a toggle function to control this state.
  • text
    AccordionTrigger
    and
    text
    AccordionContent
    are used to define the interactive parts and content display, respectively.

Step 4: Use the Components Together

Finally, compose these subcomponents together in the parent component to build the complete UI.

Example: Using the Accordion

jsx
1<Accordion>
2  <AccordionItem index={0}>
3    {({ isOpen, toggle }) => (
4      <>
5        <AccordionTrigger toggle={toggle}>Item 1</AccordionTrigger>
6        <AccordionContent isOpen={isOpen}>
7          Content for Item 1
8        </AccordionContent>
9      </>
10    )}
11  </AccordionItem>
12  <AccordionItem index={1}>
13    {({ isOpen, toggle }) => (
14      <>
15        <AccordionTrigger toggle={toggle}>Item 2</AccordionTrigger>
16        <AccordionContent isOpen={isOpen}>
17          Content for Item 2
18        </AccordionContent>
19      </>
20    )}
21  </AccordionItem>
22</Accordion>

This setup allows each

text
AccordionItem
to manage its open/closed state and interact with other items via context, while the
text
AccordionTrigger
and
text
AccordionContent
subcomponents define the UI.

Example 2: Card Component

The

text
Card
component can also benefit from the compound component pattern by splitting it into logical sections:
text
CardHeader
,
text
CardBody
, and
text
CardFooter
.

Code Example

jsx
1const Card = ({ children }) => <div className="card">{children}</div>;
2
3const CardHeader = ({ children }) => <div className="card-header">{children}</div>;
4
5const CardBody = ({ children }) => <div className="card-body">{children}</div>;
6
7const CardFooter = ({ children }) => <div className="card-footer">{children}</div>;

Usage

jsx
1<Card>
2  <CardHeader>
3    <h2>Card Title</h2>
4  </CardHeader>
5  <CardBody>
6    <p>This is the main content of the card.</p>
7  </CardBody>
8  <CardFooter>
9    <button>Action</button>
10  </CardFooter>
11</Card>

Conclusion

The compound component pattern is a powerful approach for building reusable and flexible UI components. By leveraging context to manage shared state and splitting components into smaller, focused subcomponents, you can create highly customizable and maintainable UIs. This pattern enhances both the developer experience and the end-user experience, allowing for more dynamic and adaptable interfaces. Experiment with these patterns in your projects to see how they can improve the flexibility and reusability of your components. Happy coding with Compound Components!

Published on August 2, 2024