What Are Render Props In React And How To Use Them

Render Props are a useful concept in react that can be used to share code between multiple react components. Render Props are typically used when you don’t want to render something immediately or when you want to pass some extra data to the component via props. React Router uses Render Props to pass some extra data to the component that we pass to the route in the component prop.
This sounds a little ambiguous but let me demonstrate this concept by using an example from a real world that I came across while developing a react application.

We are going to write a component that will show a list of blog posts along with the pagination. We want to use this component at different places in our react application for example the home page to show all the latest posts, the category page for showing the posts of that particular category and finally on the Popular Posts page to show most popular posts.

We are going to be developing the following components to demonstrate the concept of Render Props

  1. App.js
  2. LatestPosts.js
  3. PopularPosts.js
  4. BlogPostsList.js

BlogPostsList Component will be used in all of the above components. Here is an example of how we will use Render Props in the above mentioned pages

This renderList prop is our Render Prop because it renders the blog posts list for us.
Now let’s see what our LatestPosts component looks like

We are receiving a renderList function as a prop to our LatestPosts component and we are calling the renderList function with the data i.e. posts, isFetching and error.

return (
    <div>
      <h1>Latest Posts</h1>
      {renderList({ posts, isFetching, error })}
    </div>
)

Now that we have set up our LatestPosts component let’s use it in our application in our App component.

As you can see we are passing the renderList prop to our LatestPosts component and it returns the BlogPostsList component with all the data that it requires already available in the function parameters.

<LatestPosts
    renderList={({ posts, isFetching, error }) => (
        <BlogPostsList 
        	posts={posts} 
        	isFetching={isFetching} 
        	error={error} />
    )}
/>

Now you can simply use this `BlogPostsList` component in multiple different components by just passing different data and it will just work.

<PopularPosts
    renderList={({ posts, isFetching, error }) => (
        <BlogPostsList 
        	posts={posts} 
        	isFetching={isFetching} 
        	error={error} />
    )}
/>

So that is how we can use Render Props in our code to share functionality between multiple components.

Leave a Reply