All Articles

How to Build and Scale Design Systems: Patterns for Crafting Reusable Web Components

A before-and-after comparison showcasing new design system components
A before-and-after comparison showcasing new design system components

The holiday season is approaching, and it’s a great time for folks to review what they’ve accomplished at work. While I spent much of this year re-architecting our React frontends, I also invested a good amount of time and energy into building our design system.

I took stock of the progress we made at Amazon Health Services this year, and I’m proud to say we’ve grown our Lit component library to 34 components used by at least 16 teams across 48 frontend packages.

It’s easy to trivialize the work required to build reusable web components, and it involves a lot more than just letting an AI agent slap together some components. I’m writing this post because I believe these details matter, not just because they are “good to know”, but because they have a direct connection to the user and developer experience.

Note that:

  • I’ll be writing in more general terms and leaving out Amazon-specific internals to keep this content accessible.
  • I’ll be representing custom components as <ds-*> (where ds stands for design system).
  • I’ll be covering cross-cutting patterns and considerations that are applicable to most components, instead of doing a detailed examination of individual components.
  • This is the third and final part of my series on design systems: I previously wrote about choosing a framework and design tokens.

Focus Handling

Let’s start with some of the trickier lower-level details before moving on to higher-level ones. Specifically, let’s talk about focus.

It’s convenient to think about focus handling as an isolated problem. For example, if you’re crafting a custom button component (e.g. <ds-button>), it might simply wrap a native <button> and add custom styles over it. In this context, focus handling generally comes out of the box and you don’t need to do too much custom plumbing.

In reality though, focus handling is seldom this simple.

Your Focus History Matters

First, your focus history matters. For example, with modal components (<ds-modal>), you’ll want to make sure that you keep a reference to your modal ingress (which could be a <ds-button>, for example). This is so that whenever your modal unmounts, your focus switches back to the component you were focused on before:

Switching focus back to the modal ingress after exiting a modal
Switching focus back to the modal ingress after exiting a modal

This applies to other components as well. For example, multi-selectable pills (<ds-filter-pills>) may come with a “reset” button which lets the user clear pill selections. When the user taps on the reset button, the button also gets unmounted and users lose their focus. As such, you’ll want to validate that focus is restored to the correct target: this could be the last pill item, for example.

Define Your Tab Stops

Second, make sure you define your tab stops. Each tab stop is just a spot your focus lands on while you tab through the page. It’s easy to brush this off and say: “Let’s just let the user hop through every clickable item on the page with their tab key”, but you seldom actually want this.

For example, if you’re looking to buy clothing, you don’t want to have to tab through every option for a given product dimension (e.g. “color”) before moving on to the next dimension, “size”. Instead, you want to be able to select your preferred color (e.g. “blue”) and then immediately move on to the next section.

Using the tab key to move focus from one row to the next, while using the left and right arrow keys to change the selected option within a row. Users don't need to tab through every option in a row to get to the next one.
Using the tab key to move focus from one row to the next, while using the left and right arrow keys to change the selected option within a row. Users don't need to tab through every option in a row to get to the next one.

We call these types of components twisters (i.e. variation selectors). To me, it makes more sense to have a single tab stop per twister row / dimension. For example, if you’ve configured only one tab stop per category:

  • Hitting the tab key while you’re exploring colors would automatically take you to the next twister row
  • Using the left and right arrow keys would allow you to traverse a specific row and switch between options within a row

In code, this means keeping tabindex="0" for one item in the twister row, and tabindex="-1" for the rest. When nothing is selected, the first enabled item becomes the tab stop.

Accessibility Handling

Since we’re on the topic of focus handling, it’s worth noting we’ll also want to make sure that our ARIA (i.e. aria-*) and role=... attributes are propagated correctly.

As You Build for Focus, Build for Accessibility…

For interactive controls like buttons, accordions, and links, it makes sense that aria-label, aria-pressed, aria-expanded, aria-disabled, etc. are just set directly on the inner control and that these attributes are read out to the user just as their corresponding elements get focused.

For example, given a host <ds-button> that wraps a <button> within, setting <ds-button aria-label="View product" /> isn’t quite right since the native <button> is the actual element that receives focus and has a defined role. My recommendation would be to just define a label attribute on <ds-button> and then internally set the ARIA attribute with <button aria-label=${this.label}></button>.

Note that the chances of you needing an aria-label to supplement the content within a given interactive element are also dependent on the use case. This is something you can let your consumers determine. For example, a button that simply contains the text “Remove” may require more detailed text, like “Remove product from cart”.

But Also Support Container and Display Elements

Note that just because an element is not focusable doesn’t mean it’s excluded from having ARIA set on it, since the accessibility tree differs from the set of focusable elements. There are plenty of examples of cases where we need ARIA on “unfocusable” elements:

  • A group of tabs (e.g. <ds-tab-group>) would have role="tablist" defined on the container <div> in the subtree
  • A modal (e.g. <ds-modal>) that uses a <dialog> element internally would need the dialog to reference its internal text element by its id (e.g. <dialog aria-labelledby="modal-title">)

This model of tackling accessibility by starting from interactive, focusable elements first and then broadening one’s scope to container and display elements has been a helpful mental model for me personally.

Form Handling

A major (I must emphasize, major) gotcha with shipping custom web components is that you don’t get a lot of the automatic handling that comes with wiring form controls due to the Shadow DOM. Amongst other things:

  • An <input> inside a shadow tree isn’t included in the outer form’s FormData
  • If the label and input are separate custom elements, we can’t use <label for="foo"> since the foo element (i.e. <input id="foo">) is masked
  • We can’t trigger form submissions with <button type="submit"> since the form element is also invisible to the button (and vice versa)

The good news is that most of this can still be handled by connecting the form inputs and controls with React code (e.g. form state, callback hooks, etc.).

There’s also an attachInternals API (e.g. static formAssociated = true, this._internals.setFormValue) that allows you to configure web components so that they behave like native inputs, but it requires a fair amount of manual plumbing (e.g. to replace <button type="submit">, your <ds-button> would have to support a type attribute and submit the form itself with this._internals.form.requestSubmit()).

Wrap Native Elements Wherever Possible

With some of these more finicky details (accessibility, focus, shadow DOM, etc.) out of the way, I’ll move on to some higher-level component concerns. Here’s a quick one: At the risk of stating the obvious, you’ll want to see if your custom web component can be primarily “anchored” to an existing HTML element that already does what you want.

A good example of this would be to use the details and summary elements for accordions:

<!-- ds-accordion.ts template -->
<details>
  <summary>About this product</summary>
  <div class="accordion-content">This is a great gift for Christmas...</div>
</details>

Instead of trying to plumb your own logic to ensure that the accordion is announced as a collapsible / expandable element to screen reader users, you pretty much get this out of the box.

Another example of this is to use the native <dialog> for modals, since it gives you valuable features, such as focus containment and top-layer placement (no z-index battles), out of the box.

In a nutshell, avoid re-building details that native elements already give you.

Events Up, States Down

There are two points I’d like to make here. The first is to let web components communicate with their consumers and parents using events over callback properties. This means firing an event with:

// ds-accordion.ts
this.dispatchEvent(new CustomEvent("ds-accordion-toggle", { 
  bubbles: true, // Bubble up the DOM tree  
  composed: true, // Propagate across shadow DOM
  detail: { expanded: this.expanded },
}));

I say “consumers and parents”, because there are two similar but different use cases to highlight:

  1. How consumers (e.g. React components) use your design system library, and
  2. How parent web components (e.g. accordion group) might communicate with child web components (e.g. individual accordions)

The odds that your design system only vends a flat list of components are pretty low. It’s more likely that you’ll have scenarios where you need to support component sets, such as groups of accordions, tabs, filter pills, carousel items, etc.

As an example, here’s an accordion group (ds-accordion-group) that wraps multiple accordions (ds-accordion):

An accordion group wrapping four accordions. In this example, "arc-" is used to prefix components (i.e. the prefix serves the same function as "ds-").
An accordion group wrapping four accordions. In this example, "arc-" is used to prefix components (i.e. the prefix serves the same function as "ds-").

Why Bubble Events to Parents?

With an event-based approach, we can set up a single event handler and listener on the parent component:

// ds-accordion-group.ts 
this.addEventListener("ds-accordion-toggle", this._handleToggle)

Here, the onus would be on ds-accordion components to fire toggle events so that the parent is notified if the child accordion has opened.

Conveniently, if some parent in the consumer code that exists much higher up the tree (e.g. analytics SDK in React) decides that it wants to track this event, it can do so easily.

Conversely, if we use callback properties, it puts more weight on parent components to apply these callbacks:

// ds-accordion-group.ts 
for (const accordion of accordions) {
  accordion.onToggle = this._handleToggle;
}

Besides the fact that updating the callback may trigger a re-render (in Lit’s lifecycle), this also adds a requirement for ds-accordion-group to re-apply callbacks whenever, say, specific child accordions get added or removed. In my opinion, this type of complexity is simply not worth it.

As a bonus, if your consumers are already on frameworks that support web components, such as React 19, you can easily write your event handlers with a callback prop-like syntax:

// components/filters.tsx 
<ds-filter-group onds-filter-group-clear={() => setSelected([])}>
  <ds-filter-pill />
  <ds-filter-pill />
</ds-filter-group>

For me, this is the icing on the cake that highlights the sheer flexibility that an event-based approach offers.

Why Push States to Children?

With all that said about events, I do think parents in component sets should be responsible for setting display states on their immediate children. For example, a requirement you may see with tabs or accordions is that only one of them can be active or selected at a given point in time:

A tab group where the first active tab is marked as selected
A tab group where the first active tab is marked as selected

If we delegate this state to individual child components, we run the risk of multiple children being active at the same time. In my opinion, a cleaner approach would be to let the group component (i.e. ds-accordion-group or ds-tab-group) own this state and tell each child whether it’s selected.

// ds-tab-group.ts
this.tabs.forEach((tab) => {
  // Sync state on tab group with all child tabs
  tab.selected = tab.value === this.value;
});

We can raise this principle of “events up, states down” one level up (i.e. between consumers and top-level web components) and see it in practice with modals:

// modal-ingress.tsx
const [open, setOpen] = useState(false);
// ... 
<ds-modal open={open} onds-modal-close={() => setOpen(false)} />

If we let ds-modal manage its own open / close state, we run the risk of “state drift”. For example, if the user hits the Escape key and closes the modal, the page may still think the modal is open. Down the line, calling setOpen(true) doesn’t change anything since open would still be true.

By making sure that we bubble events for all pathways to the modal being closed (e.g. Escape key, close button, outside click) and tracking the state on the React component, we can ensure that the state remains consistent.

Quick Pointers

Before I wrap up, I’d like to add a few more quick pointers. I might update this list over time if I encounter more nuggets of wisdom in the future.

  1. Modal closure can be tricky: I made a brief point earlier that clicking outside a modal should cause it to close. There’s a nuance here - we should close the modal only if both the mousedown and mouseup events landed on the backdrop. Otherwise, a user who selects text inside the modal and releases the mouse outside of it will also experience the modal getting closed.

  2. Layout shifting in selectable lists: When building horizontally laid out text items (e.g. tabs, pills), note that bolding the selected item makes its text wider, which can nudge every item after it. It’s worth clarifying with your designer whether this is acceptable, but if it isn’t, you’ll need to “reserve” the width with an invisible bold copy of the label. You can use a zero-height pseudo-element (e.g. ::after + content: attr(data-text) + font-weight: bold) to size each item by its bold state, while hiding that copy with visibility: hidden so that screen readers don’t read it. Similarly, if you need to “underline” an item, you can use an inset box-shadow instead of changing the border value so that the content doesn’t shift.

  3. Focus rings can get clipped: A focus ring is drawn just outside an element’s box, so anything that crops or covers that area can hide it. For example, a scrollable row of tabs (overflow-x: auto) may cut off the rings that fall outside the scroll area. You can fix this by leaving a bit of padding for the ring inside the scroll container (and cancelling it out with a negative margin) so your layout doesn’t move.

  4. Don’t forget your HTML basics: After you’ve spent some time working with React templates, it’s easy to forget that in native HTML, a boolean attribute is true just by being present, whatever its value. An attribute like bold="false" will still bold a text component (ds-text). By extension, Lit will drop a reflected boolean attribute from the corresponding HTML when it’s set to false (e.g. this.bold = false). This means when writing CSS selectors, instead of keying off [bold="false"], use :not([bold]).

Final Thoughts

A design system library is, in some sense, just another API contract. Adding a new component or attribute is a lot more of a one-way door than leaving it out. You can technically address bad decisions in future major versions, but it’s still better to not introduce something you might want to remove in the future.

A common sentiment that’s arisen with AI development is that “code is cheap”. My opinion is that folks who 1) ship code to production and 2) serve on a frontline on-call rotation are the only ones who can assert this in a meaningful way. Every line of code comes with an operational and maintainability cost. Instead of letting an AI agent go wild with your design system, I suggest you aim for the leanest, smallest API that does the job.

With that, I’m wrapping up my three-part series on How to Build and Scale Design Systems.

That said, I’m not done writing about design systems, and there’s still so much I want to say about the gains I saw from re-architecting our React apps (with React 19, Vite, TanStack Query). When I get the chance, I’d like to talk more about how teams can adopt a “constraints-led approach” with AI engineering and how they can apply similar principles to their front-end architecture.