Advanced Patterns 11 exercises
Problem

Typing Higher Order Components

Higher Order Components (HOCs) allow you to wrap a component and add additional functionality to it.

Here we have an UnwrappedComponent that takes in a router and an id string:


const UnwrappedComponent = (props: { router: Router; id: string }) => {
return null;
};

We th

Loading exercise

Transcript

00:00 In this exercise, we're going to look at HOCs, or higher order components. Higher order components let you take a component, like this unwrapped component, that takes in, let's say, a proper router, router, and ID string, and you wrap it with a function.

00:15 And then you return a new component based on this function here. So we could sort of inline this if we want to. We could say, like, with router, like this, but for this example, we're not doing that. We're just going to sort of work with it as it is,

00:32 so that we can test them separately, because the unwrapped component here, it should require a router, right? Property router is missing. And the wrapped component shouldn't need a router being passed in, but also it should do validation on its props, which it's currently not doing. It seems like wrapped component is just a function that takes props any JSX element.

00:51 So your job here is to work out how to type this properly. You're going to need to definitely need to make this a generic function of some sort. We're going to need to capture the props, I think. And we need to also make sure that we type these props correctly in the new component, because we're not going to need that router prop anymore.

01:09 The other thing, final thing to mention here is this display name attribute, which is really important for HOCs, because if you're using the React DevTools and you're looking at kind of like the tree of all the React components, you want to make sure that the display name isn't duplicated and is identifiable as the thing that's been wrapped.

01:26 So this is a kind of common pattern when we're sort of using HOCs. So you might need to pay attention to that in your solution as well. So I think with that, we've got everything we need. Good luck.