Advanced Patterns 11 exercises
solution

Override forwardRef's Behavior Locally

For the first solution, let's start by looking at the actual forwardRef type from the previous explainer code:


declare module "react" {
function forwardRef<T, P = {}>(
render: (props: P, ref: React.Ref<T>) => React.ReactNode
): (props: P & React.RefAttributes<T>) => React.ReactN

Loading solution

Transcript

00:00 Okay, this is a pretty simple exercise in copy-paste. Let's go and grab the actual type from here, and let's just copy this over. We know that this is going to take in a T and a P, which is basically representing the props here. And T is going to represent the actual type of the thing that's being passed in,

00:19 or the type that we want to represent in the ref. So now we can take that render function there and basically copy and paste this over. We have a props here, which is representing P, and the ref, which is a react.ref, capturing the thing we're reffing. Then we want to return a function,

00:38 which basically takes in P and the react.ref attributes and returns a react.react node. So let's copy that over, grab that there, and let's bung that in there. Now things start working. Beautiful, beautiful, beautiful. And we've got essentially just a local declaration for our forward ref.

00:55 But there's actually a cooler solution than this, because this is actually adding just an extra function on top here, which we don't necessarily need. What we can do instead is we can just actually override it manually. So we can say, let's say, just don't save that, that's fine. Now what we've got, we've got a fixed forward ref here,

01:15 and this is a type that's representing exactly the same thing as we saw in our previous setup here. So we've got a render function here. Let me just sort of pull that down below my face a little bit, there we go, which is basically just representing the type of our fixed forward ref here.

01:32 And what we're doing is we're now saying forward ref as fixed forward ref, which behaves in exactly the same way. Whoops, I forgot to import these use refs there, dammit. Now this fixed forward ref just does all of the thing that we had captured in our big, beautiful global scope function there, but it's just local.

01:51 And again, I think this is the way to go if you don't want this to bleed out into anything that consumes this code.