Render props are the hot new react patent for building reusable components. You can think of them as dependents injection or inversion of control, depending on which wording you prefer. The idea is that you have a component that doesn’t know how to render anything. When you pass a different component into it that does know how to render something. Basically, the approach is that you build a generic component that handles the logic of your, whatever. A drop down, a search bar, or something like that.
As its property, as one of the props, it accepts another component. It says how to render something. That component that tells you how to render accepts more props. Basically, what you can do is you can have this generic component that has your logic. Pass in a child component. Because the child component is being rendered by the parent component. The parent can put props into the child component. It sounds kind of confusing when I explain it like this. It’s really not that bad. We can look at it in some code. We’ve actually used this pattern before when we were working with the react context stuff.
For a contract example, let’s build an alert on-click component, triggers a hello, world alert on any component that we click, rendered with that. Alert on-click component. Instead of knowing what it’s rendering. It’s taking its rendered component from props. That’s one of the patterns people often use. Return render. We pass in all of our props and we’re also going to pass in an on-click handler, which is going to be this dot on-click. Our on-click handler, all it has to do is alert hello, world.
We have this generic component now. To render it, we go into our AppJS, and we say alert on-click. Our render is going to be the button component. Because buttons also accept labels. We’re going to pass that in as alert hai. We now have an alert hai button. Triggers an alert. We can also make alert on-click even more flexible if we pass in a function. We can create a functional component that takes the on-click prop and renders an A tag. On-click off on-click.
The alert shows up and when we click on it, alerts hello, world. Our render prop can take anything that functions as a react component. That’s why render props are so great. You essentially get complete reusability of your logic with complete control of rendering by the users of your logic.
Know someone who wants to learn React and its whole ecosystem? Share 👇