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

Building a Simple Tabs Component

Creating Tabs, Tabs.List, Tabs.Tab, and Tabs.Panel as a compound component API.

Building a Simple Tabs Component

What you'll learn: How to structure a Tabs component using the compound component pattern to create an intuitive, flexible API.

The Core Idea

A Tabs component is a perfect candidate for the compound component pattern. Instead of passing arrays of tab data through props, you'll create Tabs, Tabs.List, Tabs.Tab, and Tabs.Panel subcomponents that work together through shared context. This makes the markup declarative and easy to understand.

The Component Structure

Your Tabs parent manages which tab is active. It provides this state through context to all children:

function Tabs({ children, defaultTab }) {
  const [activeTab, setActiveTab] = useState(defaultTab);
  
  return (
    <TabsContext.Provider value={{ activeTab, setActiveTab }}>
      {children}
    </TabsContext.Provider>
  );
}

Tabs.List is a container for tab buttons:

Tabs.List = function TabsList({ children }) {
  return <div role="tablist">{children}</div>;
};

Tabs.Tab reads the context to determine if it's active:

Tabs.Tab = function Tab({ id, children }) {
  const { activeTab, setActiveTab } = useContext(TabsContext);
  return (
    <button onClick={() => setActiveTab(id)} aria-selected={activeTab === id}>
      {children}
    </button>
  );
};

Tabs.Panel conditionally renders based on the active tab:

Tabs.Panel = function Panel({ id, children }) {
  const { activeTab } = useContext(TabsContext);
  return activeTab === id ? <div>{children}</div> : null;
};

The Result

The API becomes self-documenting and flexible:

<Tabs defaultTab="profile">
  <Tabs.List>
    <Tabs.Tab id="profile">Profile</Tabs.Tab>
    <Tabs.Tab id="settings">Settings</Tabs.Tab>
  </Tabs.List>
  <Tabs.Panel id="profile">Profile content</Tabs.Panel>
  <Tabs.Panel id="settings">Settings content</Tabs.Panel>
</Tabs>

Key Takeaway: Building compound components like Tabs involves creating a parent that manages shared state and multiple subcomponents that access that state through context, resulting in an intuitive, declarative API.