Implement a Higher Order Component with Render Props

Kent C. Dodds
InstructorKent C. Dodds

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 3 years ago

When making a reusable component, you'll find that people often like to have the API they're most familiar with, so in this lesson we'll recreate the withToggle Higher Order Component using our new ConnectedToggle render prop component.

Instructor: [00:00] You created this connected-toggle, and people are using it throughout the app to render the state of the toggle and manipulate the state of the toggle anywhere in the tree, but somebody comes to you and says, "Hey, listen. I just really like higher-order components. Could you make a higher-order component that I can use for my piece of the app?" You say, "Oh, OK. Sure."

[00:17] I'm going to go ahead and give us a shell higher-order component. We're going to implement the connected-toggle as a higher-order component. Here I created the withToggle higher-order component. It creates a wrapper component with a proper display name, prop types, wrapper component, and the non-react-statics stuff.

[00:32] Now the question is, what do we render inside of this wrapper component so that we have access to the toggled state and helpers? This connected-toggle gives us access to that. Let's go ahead, and we'll return connected-toggle. That accepts a prop called render. This is going to give us the toggle.

[00:50] Then inside of here we can render the component with the remaining props, and toggle equals toggle. With that, we can come down here and swap out the subtitle with the connected-toggle to just be a regular component that accepts a toggle prop. Then we'll wrap this in a withToggle higher-order component. Cool. Now everything seems to still work. That subtitle is still getting updated.

[01:22] We can use the withToggle, which ultimately implements the connected-toggle, or we can use the connected-toggle. This is one of the nice things about render props, is that you can implement a higher-order component using a render prop, but you can't really do it the other way around, so best to start with the render prop.

[01:38] To implement this, we created that higher-order component with the same song and dance that we normally do. Then we used our render prop and rendered the component that we're given with the remaining props and the enhancements that our higher-order component is doing for us.

magnus anderssen
magnus anderssen
~ 4 years ago

in the withToggle function we forgot to use the innerRef so that we'll loose that possibility, or did I miss something ?

Kent C. Dodds
Kent C. Doddsinstructor
~ 4 years ago

You're correct. In the video I forgot to add that bit (whoops, good thing there's an entire video dedicated to that!), but it's in the final code example.