Transform Props by using the Recompose mapProps Higher Order Component

Tim Kindberg
InstructorTim Kindberg

Share this video with your friends

Send Tweet
Published 6 years ago
Updated 4 years ago

Learn how to use the 'mapProps' higher-order component to modify an existing component’s API (its props). 'mapProps' takes incoming props and changes them however you’d like; for example, filtering the props by a field.

[00:00] I'm displaying three user lists. They're filtered by status. These are my active users, inactive, and pending. I'm doing it by using a simple user list component that I wrote, and filtering the users' array based on the status.

[00:14] I'd like to replace this block of code. I want to hide away the custom filtering logic into some custom components. Instead, we'll have three components. We'll have active users. I just want to pass it to users and have it figure out which ones are active.

[00:37] We'll have inactive users, and we'll have pending users. I'll create active users by calling a higher-order component called Filter by Status. I'm going to tell it I want to filter by the active status and I'll pass it my user list, which is the base component that I want to modify. I'll do the same thing for inactive users and pending users.

[01:14] Now, let's implement Filter by Status. Filter by Status needs to take in a status, and it needs to return a higher-order component. I'm going to make use of the map-props higher-order component from Recompose.

[01:31] Map-props takes in a function. That function takes in the props. We'll take some props in and we'll map them to some new props. The only prop I care to look at is the user's prop.

[01:46] I want to return an object, which will be the new prop object. Map-props completely blows away any props passed in. If they're not in this object, they won't be passed to the wrapped component.

[01:57] I want to pass in status and I want to pass in a new user's prop. This one will take the user's prop coming in, but filter it the same way we were doing before. I'll check if it's equal to the status that I supply.

[02:16] User list now gets the filtered users and the status. I want to add the header into my component. I'll use the status and the word users to create my header. When I refresh, everything continues to behave the same.

[02:41] If I were to change one of the user's statuses, you'll see the filtering logic continues to work.