Mar 10, 2023 - 4 min read
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.
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:
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:
1<CustomSelect>
2 <CustomSelect.Option value="1">Option 1</CustomSelect.Option>
3 <CustomSelect.Option value="2">Option 2</CustomSelect.Option>
4</CustomSelect>