The render prop pattern in ReactJs is a pattern which when used right can lead to the creation of flexible and reusable components. Learn how to create a component that applies the render prop pattern in this post.
Sometimes when creating React components, we want to make it as reusable as possible to support different use-cases. One technique to achieve this is called the Render Props technique. According to the ReactJS docs,
The term render prop refers to a technique for sharing code between React components using a prop whose value is a function.
-ReactJS docs
Furthermore,
A component with a render prop takes a function that returns a React element and calls it instead of implementing its own render logic.
-ReactJS docs
Let's say we need an AppList component and one of the requirements is to have its list items to be configurable, that is, it can render any component/ui.
We can start with something very simple like the one below:
Our AppList component can take a data prop which is any array and a renderItem prop which is a function which has a data item as its argument. The renderItem prop here is our render prop. We can use the current implementation as follows:
That works indeed. But so far we're assuming the data is just a plain array of, say, strings or numbers. How about when it is an array of objects? This should be supported by our AppList component because most of the times application data are objects.
Well, it is quite simple. Let's change our data first:
That works again but now we have a problem. Can you guess it? Open your devtools and face this error:
What is the culprit? Let us revisit the AppList component. Note that in line 14 we're passing an item called d but given our new data structure, it is now an Apostle object.
One advantage of this approach is that the user does not need to pass something like an onClick prop to the AppList itself. The user of our component can pass that directly to the very list item component being rendered by the AppList.
App.tsx
function App() { return ( <AppList data={listData} keyExtractor={(item) => item.name} renderItem={(item) => ( <button onClick={() => alert(`Hi! I am ${item.name}`)}> <span> Hi! I'm {item.name} ๐. I'm {item.age} years old. </span> </button> )} /> );}
What you have learned is not all that you can do with render props. You can also use this pattern to pass state values from one component to another. This use-case is well utilized in many React component libraries.
A time will come where we'll face the need to create components that are flexible enough to support most of our use cases. For such need, design patterns can be a great help. In this post we're able to utilize one pattern called the render prop technique to create a flexible, reusable component.