ReactJS Tutorial for Beginners -16
Welcome to part-16 of the series. You can find part-15 here. We will learn about Render props in this part. They are also used like HOC to share common functionality between components.
To understand the need for Render props, we will look into an example first. First create a new file ClickCounter2.js inside components folder.
It is a simple class based component which implements a counter. So, when we click on the button, the counter value is updated.
Next, we have a requirement to implement the same functionality on the hover of mouse. So, create a file HoverCounter2.js in the components folder. The content is almost similar to our previous file, only now we have a h2 with onMouseOver instead of a button with onClick handler.
Notice that both of the files are similar to ClickCounter.js and HoverCounter.js, which we created initially in part-14 for HOC.
Next, we will include both of them in App.js and they will be rendered on screen.
Now, as you might have noticed we are repeating the code and this is the place where Render props can help us.
The term render props refers to a technique for sharing code between React components using a prop whose value is a function.
We will first create a CounterRender.js file in the components folder. We are moving all the count and the incrementCount logic here. We are calling a function render and passing the state variable count and the incrementCount function. The function name render can be confusing, but it is the pattern and we can use anything else also.
We will also remove the code for count from ClickCounter2.js and use props to get count and incrementCount.
We will do the same for HoverCounter2.js also.
Now, finally we will see how to use them from App.js. Here, in the CounterRender we have a render props. Inside it we have a function which takes two parameters — count and incrementCount. It then calls the components ClickCounter2 and HoverCounter2, with these parameters.
Our Hover and button are working as earlier now and we had used Render props technique, to have the common logic in a place.
There is another slightly different pattern for Render props and in it we pass the component as children. The updated code is in App.js
Now, in CounterRender.js, we will use this.props.children instead of the render props.
This completes part-16 of the series. You can find part-17 here.
You can also find the code for the same in github repo, here.