Course contentsShow
← React
Lesson 1098 of 2,39628. Composition: Compound ComponentsFree lesson

Real Example: Building a Tabs Compound Component

Complete implementation of Tabs, TabList, Tab, and TabPanel sharing selected index via internal context.

Real Example: Building a Tabs Compound Component

You'll learn how to build a complete Tabs system where TabList, Tab, and TabPanel components seamlessly share the selected tab index through internal context.

The Complete Implementation

Now we'll tie everything together. Our compound component needs four pieces: a parent Tabs that provides context, a TabList container, individual Tab buttons, and TabPanel content areas. The magic is that they all coordinate through shared state hidden from the user.

Here's the mental model: Imagine a theater production where actors communicate through earpieces. The audience (component user) doesn't see the earpieces (context)—they just see coordinated performances (UI). Each actor (child component) knows exactly what to do because they're all listening to the same director (shared state).

Building the Complete System

const TabsContext = createContext(null);

function Tabs({ children, defaultIndex = 0 }) {
  const [selectedIndex, setSelectedIndex] = useState(defaultIndex);
  
  return (
    <TabsContext.Provider value={{ selectedIndex, setSelectedIndex }}>
      {children}
    </TabsContext.Provider>
  );
}

function TabList({ children }) {
  return <div role="tablist">{children}</div>;
}

function Tab({ children, index }) {
  const { selectedIndex, setSelectedIndex } = useContext(TabsContext);
  const isSelected = selectedIndex === index;
  
  return (
    <button
      role="tab"
      aria-selected={isSelected}
      onClick={() => setSelectedIndex(index)}
    >
      {children}
    </button>
  );
}

function TabPanel({ children, index }) {
  const { selectedIndex } = useContext(TabsContext);
  
  return selectedIndex === index ? <div role="tabpanel">{children}</div> : null;
}

Tabs.TabList = TabList;
Tabs.Tab = Tab;
Tabs.Panel = TabPanel;

Each child component consumes the context to access selectedIndex. The Tab compares its own index to determine if it's active and provides the setter to handle clicks. The TabPanel simply shows or hides based on the match. The parent Tabs component orchestrates everything without exposing implementation details.

Key Takeaway: A complete compound component system uses private context to coordinate multiple child components, giving users a flexible, intuitive API while keeping internal communication hidden and state management centralized.