This video is available to students only

In this lesson we'll be improving the API of the original Button component we created. Buttons are stateless and are one of the most common patterns on the web which makes them a great showcase for common shared component patterns.

In this lesson we will be covering API patterns that are applicable to all shared components. These include:

  • JSX children pass-through

  • React fowardRef API

  • JSX prop-spreading with TypeScript

  • Opinionated prop defaults

JSX children pass-through#

A core concept of React is the ability to compose elements using the children prop. Shared component design leans heavily on this concept.

Allowing consumers to provide children whenever possible makes it easier for them to provide custom content and other components. It also helps align component APIs with those of native elements.

Let's allow our Button component to render its children:

The React.FC definition already includes children as a valid prop. We can pass it directly to the native button element. Next, let's update our Storybook documentation to supply content to the Button:

forwardRef API#

Many components have a one-to-one mapping to an HTML element. To allow consumers access to that underlying element we can provide a ref prop using the React.forwardRef() API.

Providing a ref isn't something that is necessary for day-to-day React development, but it can be very useful within shared component libraries. It allows for advanced functionality, like positioning a tooltip relative to our Button with a positioning library.

Our Button component provides a single HTMLButtonElement (<button>), which we can provide a reference to with forwardRef().

To help TypeScript consumers understand what element is returned from the ref prop, we must provide a type variable that represents the element we're passing it to - HTMLButtonElement in this case.

Please select a discussion on the left.