Skip to content

Compound Components

The Course
•
20 min study

Components other people use

So far you've written components for your own screens. This week starts with components meant to be used by other developers: a team's component library, a design system, a package. Their props are an API. A good API is hard to misuse, flexible where it needs to be, and accessible by default.

All week you'll build pieces of a Study Hub, and on Day 7 you'll put them together.

One component, or several?

A tabs component could take everything as props:

JSX
<Tabs tabs={[{ value: "today", label: "Today", content: <Today /> }, ...]} />

That works until someone wants an icon in one tab, a badge in another, or a panel that isn't a direct child. Each wish becomes another prop. Compound components split the widget into parts the caller arranges:

Compound tabs React · 4 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { Tab, TabList, TabPanel, Tabs } from "./Tabs.jsx"; export default function App() { return ( <main> <h1>Study Hub</h1> <Tabs defaultValue="today"> <TabList label="Study Hub sections"> <Tab value="today">Today</Tab> <Tab value="topics">Topics</Tab> <Tab value="stats">Stats</Tab> </TabList> <TabPanel value="today"> <p>Three cards to study, about 60 minutes.</p> </TabPanel> <TabPanel value="topics"> <p>Reducers, context, refs and Suspense.</p> </TabPanel> <TabPanel value="stats"> <p>A 4-day streak.</p> </TabPanel> </Tabs> </main> ); } import { createContext, useContext, useId, useState } from "react"; const TabsContext = createContext(null); function useTabs(part) { const tabs = useContext(TabsContext); if (tabs === null) throw new Error(`<${part}> must be used inside <Tabs>.`); return tabs; } export function Tabs({ defaultValue, children }) { const [selected, setSelected] = useState(defaultValue); const baseId = useId(); return <TabsContext value={{ selected, setSelected, baseId }}>{children}</TabsContext>; } export function TabList({ label, children }) { useTabs("TabList"); return <div role="tablist" aria-label={label}>{children}</div>; } export function Tab({ value, children }) { const { selected, setSelected, baseId } = useTabs("Tab"); return ( <button role="tab" id={`${baseId}-tab-${value}`} aria-selected={selected === value} aria-controls={`${baseId}-panel-${value}`} onClick={() => setSelected(value)} > {children} </button> ); } export function TabPanel({ value, children }) { const { selected, baseId } = useTabs("TabPanel"); if (selected !== value) return null; return ( <div role="tabpanel" id={`${baseId}-panel-${value}`} aria-labelledby={`${baseId}-tab-${value}`}> {children} </div> ); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

App.jsx reads almost like HTML: <Tabs> holds a <TabList> of <Tab>s and some <TabPanel>s. The caller decides the order, the wrapping and the content. Tabs.jsx decides the behaviour:

JSX
<Tabs defaultValue="today">
  <TabList label="Study Hub sections">
    <Tab value="today">Today</Tab>
    <Tab value="topics">Topics</Tab>
    <Tab value="stats">Stats</Tab>
  </TabList>
  <TabPanel value="today">
    <p>Three cards to study, about 60 minutes.</p>
  </TabPanel>
  <TabPanel value="topics">
    <p>Reducers, context, refs and Suspense.</p>
  </TabPanel>
  <TabPanel value="stats">
    <p>A 4-day streak.</p>
  </TabPanel>
</Tabs>

How the parts talk

Tabs owns the state, selected, and shares it through a context. Every part reads it with useTabs():

JSX
function useTabs(part) {
  const tabs = useContext(TabsContext);
  if (tabs === null) throw new Error(`<${part}> must be used inside <Tabs>.`);
  return tabs;
}

export function Tabs({ defaultValue, children }) {
  const [selected, setSelected] = useState(defaultValue);
  const baseId = useId();
  return <TabsContext value={{ selected, setSelected, baseId }}>{children}</TabsContext>;
}
  • Tab marks itself aria-selected and changes the selection on click:

    JSX
    export function Tab({ value, children }) {
      const { selected, setSelected, baseId } = useTabs("Tab");
      return (
        <button
          role="tab"
          id={`${baseId}-tab-${value}`}
          aria-selected={selected === value}
          aria-controls={`${baseId}-panel-${value}`}
          onClick={() => setSelected(value)}
        >
          {children}
        </button>
      );
    }
  • TabPanel renders only when it's selected:

    JSX
    export function TabPanel({ value, children }) {
      const { selected, baseId } = useTabs("TabPanel");
      if (selected !== value) return null;
      return (
        <div role="tabpanel" id={`${baseId}-panel-${value}`} aria-labelledby={`${baseId}-tab-${value}`}>
          {children}
        </div>
      );
    }

useId gives this Tabs its own ids, so each tab's aria-controls points at its panel, and each panel's aria-labelledby points back. Two Tabs on one page never clash. (Day 5 adds arrow-key navigation, which tabs also need.)

Predict

Move one <Tab> out of the <Tabs>, for example above it. What happens?

Check your prediction

The app stops with <Tab> must be used inside <Tabs>. The parts only make sense together, and the helper hook says so in the caller's terms, not as a null error from deep inside.

Your turn

Exercise

Tell the caller

Add an optional onChange prop to Tabs, called with the new value whenever the selection changes. Use it in App to log switched to topics.

Your working space React · 4 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { Tab, TabList, TabPanel, Tabs } from "./Tabs.jsx"; export default function App() { return ( <main> <h1>Study Hub</h1> <Tabs defaultValue="today"> <TabList label="Study Hub sections"> <Tab value="today">Today</Tab> <Tab value="topics">Topics</Tab> <Tab value="stats">Stats</Tab> </TabList> <TabPanel value="today"> <p>Three cards to study, about 60 minutes.</p> </TabPanel> <TabPanel value="topics"> <p>Reducers, context, refs and Suspense.</p> </TabPanel> <TabPanel value="stats"> <p>A 4-day streak.</p> </TabPanel> </Tabs> </main> ); } import { createContext, useContext, useId, useState } from "react"; const TabsContext = createContext(null); function useTabs(part) { const tabs = useContext(TabsContext); if (tabs === null) throw new Error(`<${part}> must be used inside <Tabs>.`); return tabs; } export function Tabs({ defaultValue, children }) { const [selected, setSelected] = useState(defaultValue); const baseId = useId(); return <TabsContext value={{ selected, setSelected, baseId }}>{children}</TabsContext>; } export function TabList({ label, children }) { useTabs("TabList"); return <div role="tablist" aria-label={label}>{children}</div>; } export function Tab({ value, children }) { const { selected, setSelected, baseId } = useTabs("Tab"); return ( <button role="tab" id={`${baseId}-tab-${value}`} aria-selected={selected === value} aria-controls={`${baseId}-panel-${value}`} onClick={() => setSelected(value)} > {children} </button> ); } export function TabPanel({ value, children }) { const { selected, baseId } = useTabs("TabPanel"); if (selected !== value) return null; return ( <div role="tabpanel" id={`${baseId}-panel-${value}`} aria-labelledby={`${baseId}-tab-${value}`}> {children} </div> ); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

Tab calls setSelected. Put a select(value) function in the context that sets the state and calls onChange, and have Tab call that instead.

Hint 2: a first step

onChange?.(value) calls it only if it was passed.

Show one solution

In Tabs:

JSX
export function Tabs({ defaultValue, onChange, children }) {
  const [selected, setSelected] = useState(defaultValue);
  const baseId = useId();

  function select(value) {
    setSelected(value);
    onChange?.(value);
  }

  return <TabsContext value={{ selected, select, baseId }}>{children}</TabsContext>;
}

In Tab, read select from useTabs("Tab") and call select(value) on click. In App:

JSX
<Tabs defaultValue="today" onChange={(value) => console.log("switched to", value)}>

Was this article helpful?

Your response is saved on this device.