Compound components are a design pattern in React that allows for creating components that work together to form a cohesive unit. This pattern is particularly useful for building complex UI elements that require multiple sub-components to function correctly while maintaining a clean and intuitive API for the developer. By using compound components, developers can create more reusable and flexible components that can be easily composed together.
One of the primary benefits of using compound components is that they enable better encapsulation of logic and state. Each sub-component can manage its own state while still being able to communicate with its siblings through a shared parent component. This approach leads to cleaner code and a more organized component structure.
In a compound component setup, the parent component serves as a context provider, allowing its children to access shared state and behavior. The children components are typically designed to be flexible and can be used in various ways depending on the parent’s configuration.
const Tabs = ({ children }) => {
const [activeIndex, setActiveIndex] = React.useState(0);
const handleTabClick = (index) => {
setActiveIndex(index);
};
return (
{React.Children.map(children, (child, index) => {
return React.cloneElement(child, {
isActive: index === activeIndex,
onClick: () => handleTabClick(index),
});
})}
{children[activeIndex].props.children}
);
};
const Tab = ({ isActive, onClick, children }) => {
return (
);
};
// Usage
Tab 1
Tab 2
Tab 3
In summary, compound components provide a powerful way to build complex UI elements in React. By following best practices and avoiding common pitfalls, developers can create flexible, reusable components that enhance the overall user experience.