The PolymorphicRef Type

Understand how to type the ref property of a polymorphic component.

Let’s now turn our attention to the PolymorphicRef type. If we must support refs in our polymorphic component implementation, then we need to type the ref prop correctly.

The ComponentPropsWithRef type

So, how can we get the type of ref object passed to the rendered component, based on the as prop? The answer is by leveraging the React.ComponentPropsWithRef type!

Again, note that this component says with ref, not without ref.

Essentially, if the representation of the component props is a bundle of keys (which, in fact, it is), it will include all the relevant component props based on the element type, plus the associated ref object. Here's an illustration to help put this in perspective:

Get hands-on with 1200+ tech skills courses.