Component Props with Ref Support

Learn how to leverage the React.ComponentPropsWithRef to support refs in polymorphic components.

We'll cover the following

So far, the different iterations of the polymorphic component implementation have all leveraged the React.ComponentPropsWithoutRef type. In this section, we must support refs. To achieve this, we'll leverage the React.ComponentPropsWithRef type.

Refs in React

This is the final and most complex section of our polymorphic component solution. Let's go through every step of the code in detail.

First things first, let's review how refs in React work. The ref provides a way to access DOM nodes or React elements created in the render method of our component.

The important concept to understand here is that we don’t pass ref as a prop and expect it to be passed down into our component (like every other prop). The recommended way to handle refs in our functional components is to use the forwardRef function. It could look like this, for example:

Get hands-on with 1400+ tech skills courses.