Yesterday, we talked about how can use render props to make your components more flexible and give users of your components the chance to inject a render method into your component.
Another common pattern for what is also essentially a render prop is the so-called function as children approach. Function as children works the exact same way as render props, except that instead of providing your render function in a render prop, you provide it as a child of your component.
Basically, if you have a fancy component, you have two ways of providing render props. You can either say render here or you close this component and provide render props here in a function call.
Now, a lot of people bicker over whether you should be using render props or function as children. Really, that's kind of stupid. You should use both, or rather, your component should support both, and you should let your users decide which pattern they prefer in their code base. Like this.
Let's expand our AlertOnClick component, so with render some stuff on its own, which will make the whole function as children approach make a lot more sense. We're going to say that this is now going to be a div. This will throw an alert. Now both of our alert buttons have a little message next to them that says that this will throw an alert.
The easiest way to support both a render prop and function as children is to add an or here and say if the render prop is not defined, then we use our children, where we're using AlertOnClick. Instead of providing prop like that, we can pass in a function as our children.
It still works the same way. It's not a huge change, but I think it really adds a lot to how your component is used, because it lets your users keep a consistent code base. Some prefer a render prop, some prefer function as children. I personally prefer function as children, because it's easier to see that what you're rendering is a child of a certain component. Especially when you nest multiples, it starts making a lot more sense. If you were nesting multiple render props in an actual render prop, you kind of lose sense of hierarchy, which you keep when you're using function as children.
Really, just support both. People are weird. People do different things, and you, as a provider of a component, especially if you're making it open source, should support multiple different ways of using it so that people can keep a consistent code base and be-