Render Components Based on Predicates in Recompose

Tim Kindberg
InstructorTim Kindberg
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 6 years ago

Learn how to use the ‘branch’ and ‘renderNothing’ higher-order components to render nothing when a certain prop condition is met. Sometimes you only want to render a component when valid props exist or are in a certain condition; ‘renderNothing’ is an easy way to completely remove the component when you don’t need to show it.

[00:00] In my user management application, I'd like to feature a user, and I'd like to do it randomly. I'm currently randomly picking one user from my array of users, and I'm passing it to my featured user component. When I refresh, I should randomly get different users.

[00:19] I don't want to feature any users that are not active. I'm going to make a hideIfNotActive higher-order component, and I'll utilize the Branch higher-order component from Recompose. Branch's first parameter is a predicate. If the user is not active, then I want to renderNothing. renderNothing is another higher-order component from Recompose that just always renders null.

[00:46] Now, I need to implement the predicate user is not active. Branch predicates always take in props. I'll de-structure the status, and I'll check if status is not equal to active. If status is not equal to active, I'd like to render nothing. I need to use my new hideIfNotActive higher-order component, and now I should be able to refresh.

[01:21] When we get a user that's not active, the entire section hides. When they are active, it comes back. The reason it comes back is because implicitly, the third parameter is like an identity parameter. It's optional, and you can render something else, but by default, it will render the wrapped component, which is the featured user.

Faysal Ahmed
Faysal Ahmed
~ 6 years ago

Dear egghead:

Its look like sometimes codesandbox not editable and also not scollable.

Markdown supported.
Become a member to join the discussionEnroll Today