Compound Components in React
Expert-Level Explanation
Compound components in React are a pattern where a set of components work together to form a complete UI element while allowing the user to control their composition. This pattern provides more flexibility in terms of configuration and composition than a single monolithic component. Compound components share an implicit state and communicate with each other via React's Context API or by passing props down from parent to child.
Creative Explanation
Think of compound components, like building a custom computer. You have different parts (components) like the CPU, GPU, and RAM, which you can choose and assemble based on your needs. Each part works together to make the computer (the whole UI element), but you have the freedom to select and configure each part (component) to suit your specific requirements.
Practical Explanation with Code
An example of a compound component in React:
import React, { createContext, useContext } from 'react';
const TabContext = createContext();
const Tabs = ({ children }) => {
const [activeTab, setActiveTab] = React.useState(0);
return (
<TabContext.Provider value={{ activeTab, setActiveTab }}>
{children}
</TabContext.Provider>
);
};
const Tab = ({ index, children }) => {
const { activeTab } = useContext(TabContext);
return activeTab === index ? children : null;
};
const TabList = ({ children }) => <div>{children}</div>;
const TabPanel = ({ children }) => <div>{children}</div>;
// Usage
<Tabs>
<TabList>
<Tab index={0}>Tab 1</Tab>
<Tab index={1}>Tab 2</Tab>
</TabList>
<TabPanel>
<div>Content for Tab 1</div>
</TabPanel>
<TabPanel>
<div>Content for Tab 2</div>
</TabPanel>
</Tabs>
Real-World Example
In a web-based music player, compound components can be used for the playback controls. The mainPlaybackControl
component would manage the state, while individual components like PlayButton
, PauseButton
, and VolumeControl
would interact with this state, allowing the user to control the playback and volume.