logo
Back to blogs

Compound Components Pattern in React

Mar 10, 2023 - 4 min read

Compound Components Pattern in React

The Compound Components

The Compound Components Pattern allows you to create a collection of component that implicitly share state, offering a more flexible and powerful API for building reusable components. These components collaborate to form a single unit of functionality.

The classic example of this is <select> and <option> in HTML:

CompoundComponentsPattern.tsx
1<select> 2 <option value="1">Option 1</option> 3 <option value="2">Option 2</option> 4</select>

The <select> element manages the UI's state, while the <option> elements serve as configurations , defining the available choices anf their values. Not , imagine manually implementing this native control in React:

CustomSelect.tsx
1<CustomSelect 2 options={[ 3 { value: "1", display: "Option 1" }, 4 { value: "2", display: "Option 2" }, 5 ]} 6/>

This works fine, but it's less flexible than a compound component API, For example . What if you want to add a disabled prop to the <option> elements? With the compound components pattern, you can create a more flexible API that allows you to customize the <option> elements:

CustomSelect.tsx
1<CustomSelect> 2 <CustomSelect.Option value="1">Option 1</CustomSelect.Option> 3 <CustomSelect.Option value="2">Option 2</CustomSelect.Option> 4</CustomSelect>