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
JSX prop-spreading with TypeScript
Opinionated prop defaults
JSX children pass-through#
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
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
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.
Button component provides a single
<button>), which we can provide a reference to with
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.