learnreact.com is moving to school.reactpatterns.com. Get 50% off while we move.

Learn React

Learn React | <!-- -->Essetial React<!-- --> > <!-- -->Higher-order components

Essetial React

Higher-order components

We now have this beautiful FetchPokemon component, and it’s almost completely isolated to only thinking about fetching Pokemon data. There are two exceptions here in render. One, it can only render Pokemon, and second it has this very specific loading…. I’ve shown you two ways how to compose components in to other components, and i’d like to show you a third. The higher order component. This isn’t my favorite, but it’s very popular so you should know how to do it. It starts by wrapping this entire component class in a function. We’ll create a new function. Higher order components usually start with a with, in this case it will be withPokemon, and in their simplest form, they take a component as an argument. They then return the component class. And like what we did with component as prop, we’ll take this very specific component that we’re rendering and replace it with the component we receive as an argument. This doesn’t work yet because we haven’t used with component to compose a new component, so let’s do that. Here we’ll create a new component, and we’ll call this FetchPokemon, and this is where we compose withPokemon, the higher order component, with our Pokemon component that only cares about displaying. We’ll give this a click to make sure that everything works as it did before, and it does. So let’s review. We made a new FetchPokemon component. It’s the composition of this withPokemon higher order component function and the unknowing Pokemon component. And let’s look at those again. Pokemon defined here doesn’t know anything about fetching data. It simply takes props and assumes that it has a character to render. It’s wrapped in this higher order component function with Pokemon, which takes a component, in this case our Pokemon component, and wraps it in this, a component that knows how to fetch a Pokemon, given the prop id, and renders any component that takes character as a prop. Now the disadvantage to this is it suffers the same coupling as the component as prop pattern, where we can only use components that take very specific props. We can’t map that dynamically without some additional gymnastics. This is why I prefer the renderProp pattern.



Keep in touch!

Get notified of new React content and resources

    We respect your privacy. Unsubscribe at any time.