
Building the components: one library, one set of rules
How I structure, document and test a shared React component library, from Storybook stories and browser tests to component APIs and React Server Component boundaries.
Building the components: one library, one set of rules
In the first part, I focused on explaining the visual foundation of @konopskidev/ui: the design tokens, Tailwind theme and styles that make the library look like the rest of my applications.
But a shared UI library needs to do more than look consistent. A dialog should manage focus correctly. A button should expose a predictable API. The Storybook documentation should show the actual TypeScript types, and adding a new component shouldn't quietly introduce something that breaks a consuming application.
That's what I want to cover in this part.
The library currently contains more than 60 components. That might not sound like a huge number, but each component has several things to get right: its public props, variants, composition patterns, accessibility behaviour, documentation, tests and compatibility with both light and dark themes.
I didn't want to rely on conventions that developers have to remember. Instead, I tried to make the repository structure and tooling enforce as many of those conventions as possible.
Let's start with the smallest unit of the library.
Give every component the same structure
Every component lives next to its Storybook story and its test:
1src/components/ui/
2 button.tsx
3 button.stories.tsx
4 button.test.tsxThere are around 60 components, but almost 200 files following this structure.
This is intentional. When I add or change a component, I want its implementation, documentation and tests to be part of the same piece of work. Keeping them side by side makes that relationship visible. Thats why each component has three files living together in a components folder.
The story imports the component directly, and the test does the same. If I rename or move a component, those imports need to be updated in the same change. There isn't a separate documentation directory that can quietly become outdated.
It also gives me a simple definition of done. A component isn't finished just because it renders:
- Its public API should be typed.
- Its Storybook story should explain how to use it.
- Its behaviour should be covered by tests.
- Its visual states should be reviewable in the Storybook environment.
This structure doesn't guarantee that every component is perfect, of course. It does make missing documentation and tests much harder to overlook.
Every component has three files: implementation, documentation and tests.
Write stories as component documentation
I use Storybook 10 for component development and documentation. Each component has a story file that describes its public API and provides examples of how it can be used.
For example, the Button story starts with a metadata object:
1const meta = {
2 title: 'Components/Button',
3 component: Button,
4 tags: ['autodocs'],
5 parameters: {
6 docs: {
7 description: {
8 component:
9 'Triggers an action. The variant names are a superset of shadcn/ui: `primary` is an alias of `default`, and `ghost-primary` / `ghost-destructive` are the site’s tinted-ghost treatments.',
10 },
11 },
12 },
13 argTypes: {
14 variant: {
15 control: 'select',
16 description: 'Visual weight of the action.',
17 table: { category: 'Appearance', defaultValue: { summary: 'default' } },
18 },
19 size: {
20 control: 'select',
21 description: 'Padding scale. `default` lines up with a 40px `Input`.',
22 table: { category: 'Appearance', defaultValue: { summary: 'default' } },
23 },
24 // Every other public prop follows the same pattern.
25 },
26};The idea is to make the story useful to someone who hasn't read the component source. It should explain what a prop does, what its default value is and how it affects the component.
I also group props into categories. Common categories include Appearance, State, Behaviour, Accessibility, Composition, Content, Events and Styling. Depending on the component, I add more specific groups such as Form, Data, Range, Layout or Validation.
This makes the generated props table easier to scan. If someone wants to know how to change a button's appearance, they can find variant and size together rather than searching through event handlers and accessibility props.
There is one important distinction here: I don't want to maintain the same API information in two places. The component's TypeScript types should remain the source of truth, and Storybook should derive as much information from them as possible.
Make Storybook understand the actual TypeScript types
I ran into a small problem with the default Storybook documentation setup.
Some of the components use class-variance-authority (CVA) to define their variants. For example, a button's variant prop is inferred from the keys passed to cva(). The default react-docgen parser doesn't always resolve that type correctly. Instead of seeing a union of valid values, Storybook sees a generic string.
That affects the Controls panel. A prop that should be a select becomes a text input, which isn't particularly useful when the valid values are already defined in TypeScript.
I switched Storybook to react-docgen-typescript:
1typescript: {
2 // react-docgen cannot see through class-variance-authority, so the variant
3 // unions would degrade to `string`. The TypeScript-based docgen reads the
4 // real prop types, which is what makes the Controls panel accurate.
5 reactDocgen: 'react-docgen-typescript',
6 reactDocgenTypescriptOptions: {
7 shouldExtractLiteralValuesFromEnum: true,
8 shouldRemoveUndefinedFromOptional: true,
9 savePropValueAsString: true,
10 propFilter: (prop) =>
11 (prop.parent ? !/node_modules/.test(prop.parent.fileName) : true),
12 },
13},That fixed most of the problem, but there was one more detail.
CVA's VariantProps can include null in the inferred type. So instead of a clean union such as:
1'default' | 'primary' | 'secondary';Storybook could end up with:
1'default' | 'primary' | 'secondary' | null;The shouldRemoveUndefinedFromOptional option removes undefined, but it doesn't remove null. As a result, the Controls panel showed an empty option, and the generated props table included null in the type description.
My first thought was to define the available options manually in each story. That would work, but it would create a second source of truth. Every time I added a variant to the component, I'd also have to remember to update the story.
Instead, I added a global argTypesEnhancer that removes empty members from inferred enum types:
1const withoutEmptyEnumValues: NonNullable<Preview['argTypesEnhancers']>[number] = ({
2 argTypes,
3}) => {
4 const next = { ...argTypes };
5
6 for (const [name, argType] of Object.entries(argTypes)) {
7 if (argType?.type?.name !== 'enum') continue;
8
9 const summary = argType.table?.type?.summary;
10
11 next[name] = {
12 ...argType,
13 type: {
14 ...argType.type,
15 value: argType.type.value?.filter((value) => !isEmptyMember(value)),
16 },
17 // The docs table renders this precomputed union instead of `type.value`.
18 ...(typeof summary === 'string' && {
19 table: {
20 ...argType.table,
21 type: {
22 ...argType.table?.type,
23 summary: summary
24 .split(' | ')
25 .filter((member) => member !== 'null' && member !== 'undefined')
26 .join(' | '),
27 },
28 },
29 }),
30 };
31 }
32
33 return next;
34};The enhancer handles both the inferred enum values and the precomputed type summary used by the documentation table.
Now the component's TypeScript declaration remains the only place where variants are defined. Adding a new variant updates the component API and the Storybook controls automatically.
The Button documentation page. The variant control is a select populated from the component's TypeScript type.
Use the stories as tests, too
Once every component has a Storybook story, it makes sense to use those stories for more than documentation.
I wanted to know that every story could actually render, and that any interaction described in a story's play function worked. Rather than building a separate set of browser examples, I use the stories themselves as browser tests.
The Vitest configuration has two projects:
- A jsdom project for fast unit tests.
- A Storybook project that renders stories in a real Chromium browser.
The browser project is configured with the Storybook test plugin and Playwright:
1{
2 // Every story is a test: it must render, and its play function must pass.
3 extends: true,
4 plugins: [
5 storybookTest({
6 configDir: fileURLToPath(new URL('./.storybook', import.meta.url)),
7 }),
8 ],
9 test: {
10 name: 'storybook',
11 browser: {
12 enabled: true,
13 headless: true,
14 provider: playwright(),
15 instances: [{ browser: 'chromium' }],
16 },
17 },
18}Running pnpm test:stories starts this project. Every story has to mount successfully, and its play function has to complete.
I also configured the accessibility addon to fail the test when axe finds a violation:
1// Any axe violation fails `pnpm test:stories`.
2a11y: { test: 'error' },This catches problems that are difficult to reproduce in jsdom.
Take a Radix dialog, for example. It uses real layout, moves focus into its content, traps focus while open and returns focus when it closes. A popover may also need to flip its position if there isn't enough space. These behaviours depend on the browser environment and cannot be fully represented by jsdom.
Running the stories in Chromium also catches basic problems such as a component throwing during mount or an interaction failing when someone actually clicks through it.
There is a trade-off: browser tests are slower and require Chromium to be installed in CI. That's why I keep the two projects separate.
pnpm test runs the fast jsdom suite, which is useful during normal development. pnpm test:stories runs the browser-based Storybook tests. In CI, the browser setup includes an explicit playwright install --with-deps chromium step.
This gives me a useful split: quick feedback while developing, and a more realistic check before changes are merged or released.
Test what a component does, not how it looks internally
The jsdom tests focus on component behaviour.
A dialog is a good example because there are quite a few things to get right: opening it from a trigger, rendering it in a portal, exposing an accessible name, displaying its description and providing a way to close it.
I use a small render helper so the individual tests can focus on the behaviour they want to check:
1function renderDialog(props: DialogContentProps = {}) {
2 return render(
3 <Dialog>
4 <DialogTrigger>Open dialog</DialogTrigger>
5 <DialogContent {...props}>
6 <DialogHeader>
7 <DialogTitle>Rename article</DialogTitle>
8 <DialogDescription>The URL stays the same.</DialogDescription>
9 </DialogHeader>
10 <DialogFooter>Footer content</DialogFooter>
11 </DialogContent>
12 </Dialog>,
13 );
14}
15
16it('opens on click and names itself from the title and description', async () => {
17 renderDialog();
18
19 await userEvent.click(screen.getByText('Open dialog'));
20
21 const dialog = await screen.findByRole('dialog');
22 expect(dialog).toHaveAccessibleName('Rename article');
23 expect(dialog).toHaveAccessibleDescription('The URL stays the same.');
24});Notice what the test doesn't do: it doesn't inspect the component's class list.
Class names are an implementation detail of the visual design. In this project, many of them are also rewritten mechanically by apply-house-style.mjs, which I covered in Part 1. If I wrote tests that asserted every class string, changing the design would mean updating tests that have nothing to do with component behaviour.
Instead, I prefer to assert things that consumers rely on:
- Accessible roles and names.
- Accessible descriptions.
- Interaction results.
- Stable
data-slotattributes for component parts that don't have their own semantic role.
For example, data-slot="dialog-content" gives a test a stable way to find the dialog content without depending on a combination of Tailwind classes.
There are exceptions. Some visual rules are important enough to be part of the library's contract. The table test checks that a row uses border-b and doesn't use a shadow. The checkbox test checks its rounded-sm radius.
Those tests are deliberate. The design system uses borders instead of shadows and has one radius scale. If a future change accidentally breaks those rules, I want the tests to tell me.
The distinction is simple: test behaviour by default, and assert styling only when a specific visual rule is itself the thing being protected.
I also expose semantic state through attributes such as data-variant and data-size. For example, button.tsx exposes both. That gives tests a way to inspect the component's selected variant or size without having to infer it from the generated classes.
Make test coverage a ratchet
Having tests is one thing. Making sure new code doesn't gradually reduce the amount of tested behaviour is another.
I use Vitest's coverage thresholds to set a minimum coverage level:
1coverage: {
2 provider: 'v8',
3 include: [
4 'src/components/ui/**/*.tsx',
5 'src/lib/**/*.{ts,tsx}',
6 'src/hooks/**/*.ts',
7 ],
8 exclude: ['src/**/*.stories.tsx', 'src/**/*.test.tsx'],
9 thresholds: {
10 lines: 65,
11 functions: 60,
12 statements: 65,
13 branches: 50,
14 'src/hooks/**': {
15 lines: 90,
16 functions: 75,
17 statements: 90,
18 branches: 85,
19 },
20 'src/lib/**': {
21 lines: 70,
22 functions: 50,
23 statements: 70,
24 branches: 90,
25 },
26 },
27},The important part is that the thresholds differ depending on the kind of code.
Hooks and utilities usually contain actual logic: event subscriptions, breakpoint comparisons, string transformations and other behaviour that can be tested directly. I hold those files to higher coverage thresholds.
Most component files, on the other hand, contain a lot of class strings and prop forwarding. Setting the same high threshold for every component could encourage tests that assert markup without really checking useful behaviour.
The overall threshold still makes it difficult to add a component with no tests. The higher thresholds make sure that the parts containing more complex logic receive more attention.
I think of this as a ratchet. The thresholds establish a minimum level that the suite has to maintain. New code should not quietly lower that standard.
Extend the component APIs without fighting upstream
The shadcn registry is a starting point, not the final API of the library.
I want to preserve the useful parts of the upstream components, but I also need them to fit the conventions of my applications. The rule I follow is to add house-specific functionality on top of the existing API rather than replacing it unnecessarily.
Button is a good example. It keeps the familiar shadcn variants and adds a few options that match the design of my website:
1const buttonVariants = cva(
2 'inline-flex shrink-0 cursor-pointer items-center justify-center gap-2 rounded-sm border border-transparent font-sans text-sm font-medium whitespace-nowrap focus-ring transition-colors disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*=size-])]:size-4',
3 {
4 variants: {
5 variant: {
6 default: 'bg-primary text-primary-foreground hover:bg-primary/90',
7 primary: 'bg-primary text-primary-foreground hover:bg-primary/90',
8 secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80',
9 destructive: 'bg-destructive text-destructive-foreground hover:bg-destructive/90',
10 outline: 'border-border bg-background hover:bg-accent hover:text-accent-foreground',
11 ghost: 'bg-transparent hover:bg-accent hover:text-accent-foreground',
12 'ghost-primary': 'bg-transparent text-primary hover:bg-primary/10',
13 'ghost-destructive': 'bg-transparent text-destructive hover:bg-destructive/10',
14 link: 'text-primary underline-offset-4 hover:underline',
15 },
16 size: {
17 default: 'px-4 py-2.5',
18 xs: 'gap-1 px-2 py-1 text-xs [&_svg:not([class*=size-])]:size-3',
19 sm: 'px-3 py-1.5 text-sm',
20 lg: 'px-6 py-3',
21 'icon-xs': 'p-1.5 [&_svg:not([class*=size-])]:size-3',
22 'icon-sm': 'p-2',
23 icon: 'p-2.5',
24 'icon-lg': 'p-3',
25 },
26 },
27 defaultVariants: {
28 variant: 'default',
29 size: 'default',
30 },
31 },
32);For example, primary is an explicit alias for default, while ghost-primary and ghost-destructive provide the tinted ghost styles used by the site.
The sizing is also intentional. The default button uses padding rather than a fixed height. That makes it line up with the 40px input without having to maintain the same height value in two separate components.
The same approach applies elsewhere. Badge gains a tag variant for the muted pills used on cards. Card gains an interactive option for cards that behave as links. Dialog gets additional composition props, which I'll get to in a moment.
Evolve APIs without unnecessarily breaking consumers
A shared library needs to be careful when changing public props. Once another application uses a component, its API becomes a dependency.
One example is DialogContent.
The original API exposed:
1showCloseButton?: boolean;That was enough to show or hide the default close button, but it didn't give consumers a way to provide a different close affordance. This became a problem when a dialog was rendered on a surface other than the default background, where the built-in close button might not have enough contrast.
I changed the API to accept a more flexible closeButton prop:
1closeButton?: boolean | React.ReactNode;The old showCloseButton prop remains available but is deprecated:
1/**
2 * @deprecated Use `closeButton` instead. Kept so existing call sites keep
3 * working; `closeButton` wins when both are set.
4 */
5showCloseButton?: boolean;If both props are provided, closeButton takes precedence.
This lets existing call sites keep working while giving new consumers a better API. The type also makes the preferred replacement clear to anyone reading the component definition.
Prefer composition to class overrides
The dialog is also a good example of why I sometimes need to change more than the props.
The registry's default dialog is a centred card. It has a border, radius, padding, shadow and entrance animation. That's a good default for a form or confirmation dialog.
But what if I want to build an image viewer or a full-screen canvas? In those cases, I don't want the card surface at all.
Before adding a dedicated variant, the only way to get the desired result was to cancel the default classes at every call site, sometimes using !important. That made the consumer responsible for knowing which styles needed to be overridden, and those overrides could easily become outdated when the component changed.
I decided to make the dialog composable instead.
The bare variant uses a minimal full-screen layer:
1/**
2 * The bare layer: full viewport, none of the card chrome and no entrance
3 * animation. A viewer that already covers the screen has nothing to fly in.
4 */
5const BARE_CONTENT_CLASS =
6 'fixed inset-0 z-[var(--z-index-modal)] outline-none focus-visible:outline-none';The component also exposes a few props for controlling the backdrop and close affordance:
1type DialogContentProps = React.ComponentProps<typeof DialogPrimitive.Content> & {
2 closeButton?: boolean | React.ReactNode;
3 /** Classes for the backdrop. The layer is not otherwise reachable. */
4 overlayClassName?: string;
5 /** Render the backdrop at all. Defaults to `true`. */
6 showOverlay?: boolean;
7 variant?: 'default' | 'bare';
8};With variant="bare", consumers can remove the default card styling while keeping the dialog behaviour. overlayClassName lets them style the backdrop, and showOverlay lets them remove it entirely.
For layouts that need more control than these props provide, the library also exports DialogContentPrimitive.
The important point is that the consumer no longer needs to know which default classes to cancel. The component exposes the composition options directly.
The same dialog behaviour, composed in two ways. The bare variant removes the card surface while retaining the focus trap, Escape handling and accessibility wiring.
A lesson from the CardImage API
Not every attempt at making an API flexible turns out well. CardImage is probably the best example of a decision I had to revisit.
The first version accepted src, alt and an imageComponent prop. The idea was to support Next.js applications using next/image, while allowing other applications to fall back to a regular <img>.
It looked flexible, but it introduced a framework-specific concept into a framework-independent library. I also had to account for Next.js-specific props such as fill, map them to the right component, and deal with the fact that an image source could be missing.
The result was more complicated than the problem it was trying to solve.
In release 0.2.0, I reverted that API. CardImage now owns only the aspect-ratio container and accepts the media as children:
1interface CardImageProps {
2 aspect?: string;
3 className?: string;
4 /**
5 * The media itself. Required on purpose: an aspect box with nothing in it is
6 * never the intended result, and making it optional pushed every call site
7 * into guarding the frame with its own conditional.
8 */
9 children: React.ReactNode;
10}A Next.js application can pass next/image, a Vite application can pass an ordinary <img>, and an Astro application can pass its own image component.
The library owns the frame and its aspect ratio. The consuming application owns the actual media element.
Making children required was a breaking change in a 0.x release, but it made the API simpler and removed the need for every call site to guard against an empty image frame.
This was a useful reminder that flexibility isn't always the same as a good abstraction. Sometimes the better API is the one that has fewer responsibilities.
Treat React Server Component boundaries as part of the API
There's another concern that isn't visible in the component's appearance or its Storybook story: the React Server Component boundary.
A library can work perfectly in a client-rendered application and still cause problems when a consumer uses React Server Components.
In an RSC tree, a module that uses hooks or wraps a primitive that doesn't declare its own client boundary needs to be marked with 'use client'. Without that directive, the consumer can get a runtime error.
But there is a cost to adding the directive everywhere. It marks the entire module as a client module, which can move more code into the client bundle than necessary.
I wanted to enforce both sides of the rule:
- Components that genuinely need a client boundary must have one.
- Components that don't need one shouldn't get marked unnecessarily.
I added a test that inspects the source and determines whether a module needs the directive:
1function needsClient(source: string): boolean {
2 return (
3 /\buse[A-Z]\w*\s*\(/.test(source) || radixPrimitives(source).some((name) => name !== 'Slot')
4 );
5}The test checks for hook calls and Radix primitives that don't provide their own client boundary. Slot is excluded because it is just the asChild composition mechanism and doesn't need to be marked.
There are also dependencies that already declare their own client boundary. Components wrapping packages such as cmdk, sonner, react-resizable-panels and @shadcn/react/questionnaire don't need to add another directive themselves.
I don't want to assume those dependencies will always behave the same way, though. The test reads their installed package source from node_modules and checks that the directive is still present. If a dependency update removes it, the test catches the change before it reaches a consumer.
Why I don't just mark every Radix component as client-side
This rule came from an actual problem.
During the 0.2.0 work, I initially marked every module that imported a Radix primitive as a client module. It looked like the safe option, but it broke a common usage pattern:
1Attempted to call buttonVariants() from the serverThe button.tsx module exports both the Button component and the buttonVariants helper. The helper is a plain function used to calculate classes. It doesn't need to run in the browser.
However, 'use client' applies to the entire module, not just the component that uses the client-side functionality. Marking the file made buttonVariants a client reference too.
That caused problems when a consumer tried to use the helper to style a link from a Server Component — a normal use case for the asChild pattern.
The solution was to narrow the rule. A module needs the directive when it calls a hook or wraps a primitive that doesn't declare its own boundary. It doesn't need one just because it imports something from Radix.
The test now checks both directions, so adding a directive unnecessarily is also caught.
The trade-off is asymmetric: a missing directive can cause a runtime error in the consumer's application, while an unnecessary directive can increase the client bundle. Both matter, but they are different kinds of problems, and the repository should make that distinction explicit.
Don't let a green test suite replace a review
Even with stories, unit tests, browser tests and coverage thresholds, I don't think a green test suite proves that a component library is complete.
Tests only verify the behaviour someone thought to test. They don't necessarily tell you that a component is missing an important feature or that its API is awkward to use.
I learned this while doing a review pass I called "10 UI library gaps".
The pass identified several areas worth checking:
- Success colour tokens.
CardTitlesupport forasChild.- The
CardImageAPI. - A
tagvariant forBadge. - Table cell spacing around checkboxes.
- The
lucide-reactpeer dependency. - A few dialog details.
Some of these resulted in actual changes. For example, CardTitle gained asChild, so consumers can choose the correct heading level without losing the component's display styling.
The table's checkbox-cell selector also needed an update. It changed from:
1[&:has([role=checkbox])]:pr-0to:
1has-[[role=checkbox]]:pr-0The latter is the syntax needed for the Tailwind CSS v4 setup.
Other items were already implemented, cosmetic, or never made it into the final diff. That's fine. A review checklist is a way to investigate potential gaps, not a promise that every item must result in a code change.
The CardImage API change was one of the changes from that pass, and it was later reverted in 0.2.0, as described above.
That's probably the most useful lesson from the exercise: a review should be allowed to challenge earlier decisions, including decisions that were recently implemented. A green build tells me that the code satisfies the checks I have written. It doesn't tell me that the component is the right abstraction or that it provides everything the application needs.
For that, I still need to read the components, compare them with the applications they serve and try using them in real layouts.
What this structure gives me
The structure comes with a cost. Writing a useful story can take longer than writing a small component. Tests need to be maintained, and the coverage thresholds make an untested addition harder to ship.
But it also means that the repository can answer most questions about itself:
- What values can
variantaccept? Read the TypeScript type. - How should I use this component? Open its Storybook story.
- What behaviour does it promise? Read its tests.
- Does it work in light and dark themes? Check the stories.
- Does it need a client boundary? The boundary test checks it.
That's the consistency I wanted when I started building the library. Not just components that happen to look alike, but components with predictable APIs and behaviour, documented and tested in the same place.
In Part 1, I covered the design foundation that makes the library look consistent. This part was about making the components themselves consistent.
There's one final piece: turning all of this source code into something another application can install.
In Part 3, I'll walk through the package build, the generated JavaScript and TypeScript declarations, the package exports, and the GitHub Actions workflow that prepares and publishes a release.