Use Prop Collections with Render Props

Kent C. Dodds
InstructorKent C. Dodds

Share this video with your friends

Send Tweet
Published 4 years ago
Updated a year ago

Sometimes you have common use cases that require common props to be applied to certain elements. You can collect these props into an object for users to simply apply to their elements and we'll see how to do that in this lesson.

Instructor: [00:00] Often, users of the component that exposes our render prop API will have common use cases. For example, pretty much every user of the toggle component here is going to want to render a button that can toggle the state.

[00:11] Here, we have two. Our API is going to change slightly so we can support this common use case. We are going to expose a toggler props object, which can be spread across any toggler button that our consumers want to render.

[00:24] We are passing this.getStateAndHelpers to this.props.children. Let's go ahead and add a toggler props object here. This is going to have an OnClick handler for this.toggle and aria pressed is this.state.on.

[00:42] Now, this functionality totally works. The consumer of our API doesn't need to concern themselves about what it takes to wire up these two buttons to be togglers and this toggle component.

[00:52] In the future, we could change onClick to onKeyDown, if that made more sense. That could be an implementation detail of the toggle component. It allows consumers to apply the toggler props object to any button that they are rendering which fits this use case.

Alexis Duran
Alexis Duran
~ 3 years ago

First, let me tell you I am having a blast with this course so far, really like all this course of patterns (I would love to see more courses of this type). But in other hand, talking about this lesson, what is not yet clear for me is how passing "togglerProps" to the consumer components is any different that the "on" and the "toggle" we used to pass?

Cheers, and sorry if it is too silly.

Christian
Christian
~ 3 years ago

Hi Alexis, it's about hiding the implementation details from the user of this component (listen the last bit of the tutorial again). See Kent's Downshift example https://github.com/paypal/downshift#usage You don't have to care about each and every prop that you pass into the relevant component, just spread...

Alexis Duran
Alexis Duran
~ 3 years ago

Thanks for the response Christian, I didn't realize you have answered it. Cheers!

Nazariy
Nazariy
~ 2 years ago

But render props aren't great for performance, right? Because that render props function gets re-created every time.