Current section: Imperative Handles 36 exercises
solution

useImperativeHandle

Loading solution

Transcript

00:00 All right, Marty Moneybag gave us our API type, which is nice. So we're going to have a scroll to the bottom and scroll to top in reverse order right there. And then we're going to need a scrollable ref prop. We could call it just ref, but I don't know. It just kind of feels right to call it scrollable ref.

00:18 The type for this is a ref object that implements the scrollable imperative API, or it could be null because we don't actually get it set until it comes into scrollable. So that's why it could be null, because it's going to initialize as null,

00:34 and we're going to set it in our component here. All right, so with that now, we're going to say use imperative handle and pass the scrollable ref, and then a function that will assign the scroll to top and scroll to bottom for us automatically, which is quite nice.

00:53 Feel free to, I'm not going to bother with the dependency array, but you feel free to add a dependency array to yourself and see how things kind of spider out from there. Dependency arrays are the worst. Okay, great. So now if they provide a scrollable ref prop, which they should because their types require it,

01:13 then that scrollable ref prop will get these two functions added. So from there, they can call those and it will scroll where it's supposed to go. So let's create that prop here. It's a use ref. Here's our scrollable imperative API or null. We're going to initialize it to null,

01:32 and here's our scrollable ref. So then down here, let's add that scrollable ref to there. And so now we have an object that has methods we can call to effectuate change inside of our scrollable component. So here are scroll to top.

01:51 We can, whoops, say scrollable ref, there it is, dot current. If that exists, then we'll call scroll to top on it. And it will exist. But TypeScript wants us to make sure. If we don't include that, then TypeScript's like, oh, it might not. And it's true. Technically, it might not. There's nothing in here that ensures TypeScript

02:10 that it will. So with that now, if I click scroll to top, boom, go to the top, scroll to the bottom, go to the bottom, up to the top, down to the bottom, looks awesome. So this is the imperative API that allows us to effectuate change inside of a component from a parent.

02:30 And that works out really nicely for the occasional case where you actually need to have some sort of imperative interaction with the child's component. This is a perfect example of a situation like that. All right, there you go, well done.