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

Example: Building a Complete Tabs Component

Walk through a full implementation of a tabs compound component from planning to final API.

Example: Building a Complete Tabs Component

You'll learn: How to combine all compound component patterns into a fully functional, flexible Tabs component from start to finish.

The Complete Picture

Now we'll build a real tabs component that demonstrates everything: context-based state sharing, flexible composition, named children, and optional render props for ultimate flexibility.

The Full Implementation

Here's how all the pieces fit together:

// 1. Set up context and types
const TabsContext = React.createContext(null);

function useTabs() {
  const context = React.useContext(TabsContext);
  if (!context) throw new Error('Tabs compound components must be used within Tabs');
  return context;
}

// 2. Parent component with state
function Tabs({ defaultValue, children }) {
  const [activeTab, setActiveTab] = React.useState(defaultValue);
  
  const value = React.useMemo(
    () => ({ activeTab, setActiveTab }),
    [activeTab]
  );

  return (
    <TabsContext.Provider value={value}>
      <div className="tabs">{children}</div>
    </TabsContext.Provider>
  );
}

// 3. Named child components
Tabs.List = function TabsList({ children }) {
  return <div className="tabs-list" role="tablist">{children}</div>;
};

Tabs.Tab = function Tab({ value, children }) {
  const { activeTab, setActiveTab } = useTabs();
  return (
    <button
      role="tab"
      aria-selected={activeTab === value}
      onClick={() => setActiveTab(value)}
    >
      {children}
    </button>
  );
};

Tabs.Panel = function TabsPanel({ value, children }) {
  const { activeTab } = useTabs();
  if (activeTab !== value) return null;
  return <div role="tabpanel">{children}</div>;
};

// 4. Usage
<Tabs defaultValue="profile">
  <Tabs.List>
    <Tabs.Tab value="profile">Profile</Tabs.Tab>
    <Tabs.Tab value="settings">Settings</Tabs.Tab>
  </Tabs.List>
  <Tabs.Panel value="profile">Profile content</Tabs.Panel>
  <Tabs.Panel value="settings">Settings content</Tabs.Panel>
</Tabs>

Key Takeaway: A complete compound component combines context for state sharing, named children for clear APIs, proper validation, and flexible composition—resulting in an intuitive, powerful developer experience.