Understanding Render Props in React

But using an easier example

React Render Props Tutorial

React Docs are awesome. I use it all the time but I found the examples used in the render props documentation over-complicated. It certainly went over my head the first time around.

So, I’m writing this quick post for those of us who found themselves scratching their heads after going through that render prop explanation in the official documentation.

In simple words, a render prop is a way to pass a template to a component which should be used while rendering, on the fly.

For example, let us suppose that we have a following component which renders various items in a list format.

class App extends React.Component {
render() {
return (
<div>
<ul>
<ListItem data={2} />
<ListItem data={7} />
<ListItem data={2} />
<ListItem data={4} />
<ListItem data={9} />
</ul>
</div>
)
}
}

What if we wanted to render certain list items in ways different than the rest? How could we do that? A render prop is an answer to that.

It allows us to not hard-code everything inside our components. It also saves us from the trouble of composing several similar-looking components which only differ slightly in how they render their contents.

Here is how you can use a render prop to pass templates to the ListItem components about how they should render the contents.

class App extends React.Component {
render() {
return (
<div>
<ul>
<ListItem render={data => <div>{data}</div>} data={2} />
<ListItem render={data => <div><b>{data}</b></div>} data={7} />
<ListItem render={data => <div>{data*3}</div>} data={2} />
<ListItem render={data => <div><i>{data}</i></div>} data={4} />
<ListItem render={data => <div>{`Value: ${data}`}</div>} data={9} />
</ul>
</div>
)
}
}
The render prop is a function which returns a React element.

Here I’ve named it render (See ListItem), but you can name it whatever you like. But how can we consume these render props inside our ListItem component? Like this:

class ListItem extends React.Component {
render () {
return (
<li>
{this.props.render(this.props.data)}
</li>
)
}
}

In short, the ListItem component is just going to call the render method which has been passed in as a prop and pass the other prop i.e. the data prop, as an argument to that method.

So this will return a <li> element, wrapping a div containing the content of our list item. I hope the above example made sense to you. A working copy of the same is embedded below.


If you have any queries or doubts, hit me up on Twitter @rajat1saxena or write to me at rajat@raynstudios.com. Please recommend this post, if you liked it and share it with your network.

Twitter|YouTube|Rayn Studios

Till next time…