This video is available to students only

The patterns used in the previous module work well for simple, standalone elements. But, once you start creating patterns that share state between components, additional logic is required.

In this module we will create a collection of form controls as compound components. These components will have a shared React Context provider that stores an auto-generated ID for accessibility.

API design#

Compound components are a useful design pattern because they increase the flexibility of a component. Let's look at a traditional component API for a form field.

Fields often have two DOM elements, label and input. These fields share a common ID which requires us to abstract the elements to a single component.

This API helps ensure a common layout, but can lead to flexibility issues in the future. Without providing separate components for each DOM element, consumers are unable to change the order of elements or style them individually. It also makes it difficult to provide consistent props for each element; would an onClick event be for the label or input element?

Start a new discussion. All notification go to the author.