Sub topic 9
Attaching subcomponents and guarding misuse
This chapter assumes you can write function components and use useState and useContext. It also assumes you have seen the Tabs example from the previous chapter, where Tabs shares its selected value through context. Here you will look at two details that decide whether a compound component is pleasant to use: how the subcomponents are exposed, and what happens when someone uses them wrongly.
Why attach subcomponents to the parent
A compound component is only useful if consumers can find its parts. There are two common ways to expose them.
- Separate named exports:
import { Tabs, Tab, TabPanel } from './tabs'. - Static properties on the parent:
import { Tabs } from './tabs', then<Tabs.Tab>and<Tabs.Panel>.
Static properties make the relationship visible in the JSX. A reader sees Tabs.Tab and knows the tab belongs to Tabs. The consumer needs one import, and generic names such as Tab or Panel cannot collide with other components in the file.
A function in JavaScript is an object, so you can add properties to it. React does not treat these properties specially. Tabs.Tab is an ordinary function stored under the key Tab, and JSX accepts it because a member expression such as Tabs.Tab is a valid element type.
Two ways to attach
The first way is assignment, as in the Tabs example:
Tabs.Tab = Tab;
Tabs.Panel = Panel;The second is Object.assign, which builds the public component in a single expression:
export const Tabs = Object.assign(TabsRoot, { Tab, Panel });Object.assign copies the listed properties onto TabsRoot and returns that same function. The advantage is that the export is created once and complete. Nobody can import a Tabs that is missing its parts because a later line has not run yet. It also works better with TypeScript, which infers the combined type without extra declarations.
A complete guarded version
The next example puts the pieces together. It adds a guard hook, a displayName on the context, and a check that fails with a message that names the offending component.
import { createContext, useContext, useState } from 'react';
const TabsContext = createContext(null);
TabsContext.displayName = 'TabsContext';
function useTabs(componentName) {
const ctx = useContext(TabsContext);
if (ctx === null) {
throw new Error(`<${componentName}> must be rendered inside <Tabs>`);
}
return ctx;
}
function TabsRoot({ defaultValue, children }) {
const [value, setValue] = useState(defaultValue);
return (
<TabsContext.Provider value={{ value, setValue }}>
<div>{children}</div>
</TabsContext.Provider>
);
}
function Tab({ value, children }) {
const { value: active, setValue } = useTabs('Tabs.Tab');
return (
<button role="tab" aria-selected={active === value} onClick={() => setValue(value)}>
{children}
</button>
);
}
function Panel({ value, children }) {
const { value: active } = useTabs('Tabs.Panel');
return active === value ? <div role="tabpanel">{children}</div> : null;
}
export const Tabs = Object.assign(TabsRoot, { Tab, Panel });Function declarations are hoisted, so Object.assign on the last line can safely reference Tab and Panel.
How the guard works
The guard depends on one decision: the context default is null. When a component calls useContext(TabsContext) and no Tabs.Provider is above it, React returns the default value. The guard recognizes null as "no provider" and throws.
This check is only as strong as the default. If you wrote createContext({ value: undefined, setValue: () => {} }) to avoid a null check, the guard would never fire. A misplaced Tabs.Tab would render, and clicking it would do nothing. A thrown error at the first render is much easier to debug than silent inaction.
The guard lives in a custom hook rather than inside each subcomponent. This keeps the check in one place, and every subcomponent gets the same behavior by calling useTabs.
Writing useful error messages
An error message should answer three questions: which component failed, what it needs, and where it was expected. Compare these two:
Cannot destructure property 'value' of null<Tabs.Tab> must be rendered inside <Tabs>
The first message is what you get with no guard. It points at a line inside your library and says nothing about the cause. The second one tells the consumer what to fix. Passing componentName into the hook costs one argument and saves real debugging time.
Naming for React DevTools
React DevTools shows components by their function name. Functions declared as function Tab() have good names. Problems appear when you wrap components in memo, forwardRef, or an anonymous arrow function. DevTools then shows Anonymous or ForwardRef. Set displayName when that happens:
import { forwardRef } from 'react';
const Tab = forwardRef(function Tab({ value, children }, ref) {
const { value: active, setValue } = useTabs('Tabs.Tab');
return (
<button ref={ref} role="tab" aria-selected={active === value} onClick={() => setValue(value)}>
{children}
</button>
);
});
Tab.displayName = 'Tabs.Tab';Setting TabsContext.displayName earlier has the same purpose. DevTools shows TabsContext.Provider instead of a generic Context.Provider.
Gotchas
- Wrapping loses statics. If you wrap
Tabsafter attaching, as inmemo(Tabs)or a higher-order component, the result may not carryTabandPanel. Attach the subcomponents to the final exported value, after all wrapping. - Statics and bundlers. With static properties, importing
Tabspulls in every subcomponent. Separate named exports can be tree-shaken individually. For small parts this rarely matters. - Server and client boundaries. In frameworks that split server and client components, member access such as
Tabs.Tabcan fail across the boundary, because the client module exports only the reference to the parent. If you use such a framework, prefer named exports for the parts. - Guards check placement, not correctness.
useTabsconfirms that a provider exists. It does not confirm that<Tabs.Tab>is inside atablist, or that avaluematches any panel. Validate those separately, for example with a development-only warning. - Children are not restricted. Context lets consumers wrap subcomponents in their own elements, which is a feature. Do not rely on
React.Childreninspection to check structure, since it breaks as soon as someone adds a wrapper.
Choosing between the two shapes
Use static properties when the parts only make sense together, as with Tabs, Menu, or Accordion. Use named exports when parts are useful alone, or when your framework's module boundaries make dot notation risky. Both shapes can share the same guard hook, so the choice affects imports and nothing else.
Exercise
A teammate changes the context line to createContext({ value: null, setValue: () => {} }) to avoid null checks, and useTabs still tests ctx === null. A developer renders <Tabs.Tab value="a"> outside any <Tabs>. What happens, and how do you fix it?
Show answer
The tab renders without an error, because useContext returns the default object, which is not null. Clicking it calls the empty setValue and nothing changes. Restore createContext(null) so the guard fires and throws <Tabs.Tab> must be rendered inside <Tabs>.
Exercise
You export export const Tabs = memo(TabsRoot) after writing TabsRoot.Tab = Tab;. Consumers report that Tabs.Tab is undefined. Why, and what is a safe fix?
Show answer
The statics were attached to TabsRoot, but the export is the object returned by memo, which does not copy them. Attach after wrapping, for example export const Tabs = Object.assign(memo(TabsRoot), { Tab, Panel });.