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:
AccordionCardWhy 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
AccordionSteps 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
AccordionExample: Accordion Context
jsimport { createContext, useContext, useState } from 'react'; const AccordionContext = createContext();
Here,
AccordionContextStep 2: Create the Parent Component
The parent component (e.g.,
AccordionExample: Accordion Component
jsx1const 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
AccordionAccordionContextStep 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
jsx1const 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:
- uses the context to determine if it should be open and provides a toggle function to control this state.text
AccordionItem - andtext
AccordionTriggerare used to define the interactive parts and content display, respectively.textAccordionContent
Step 4: Use the Components Together
Finally, compose these subcomponents together in the parent component to build the complete UI.
Example: Using the Accordion
jsx1<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
AccordionItemAccordionTriggerAccordionContentExample 2: Card Component
The
CardCardHeaderCardBodyCardFooterCode Example
jsx1const 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
jsx1<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!