A render prop is a function you provide to a custom component, for the purpose of controlling how that component renders content.
The react props object provides any kind of data you might want a component to receive from an outer component, or from a state management library such as Redux. A component can be very flexible because it can make use of anything outside of itself to modify itself internally.
You can also pass functions as a prop aside from data. You typically use these functions as callback functions to the parent component, that you can trigger once something in your child component has changed.
The ability to pass functions provided an interesting pattern developers began to use, called render props. Render props are cool because you can affect what is rendered by your child component, from your parent component.
render () {
return <MyComponent myRenderProp={this._myRenderPropFunction}/>
}
//Inside of "MyComponent"
render () {
return this.props.myRenderProp();
}
With this setup, the function _myRenderPropFunction
in the parent, will be triggered on each render. This gives you a lot of flexibility, because your child component just renders the output of the function you passed into it, and the parent component now has control over the rendered output.
This is useful when you can't anticipate what will be rendered by your component and you need it to be as flexible as possible. This especially useful when building a custom component library, where you may want to give the developer the flexibility on deciding what to render within your library component, without modifying your library's code to fit their needs.
We can pass arguments to the render prop, just like we do when we call callbacks in our components. The arguments can be internal state data, that your parent component has no access to otherwise. It could be used to pass ids, or items, or any type of data, that lets you know what is going on inside your component when your render prop is called. The parent component can use this info to help it determine what needs to be rendered at that point.
Child component:
//Inside of "MyComponent"
render () {
return this.props.myRenderProp(some, internal, params)
}
Parent component:
_myRenderPropFunction = (some, internal, params) => {
console.log(some, internal, params);
};
It is a very simple set up, but the benefits should be easy to see. The children items in your custom component are now "variable", and can be anything you want to pass into it, at runtime.
Render props are all about flexiblity for your projects and libraries?
This sort of setup helps you solve a lot of complex rendering issues. If you feel like your child component needs to render different elements based on its use, then render props are a great way to go!