React render prop Pattern with Example

react
Back

React render prop is yet another technique for sharing code between React components next to HOC pattern.

Lets have a look at below code

<ComponentWhichCodeCanBeReused
render={(data) => <h1>Hello {data.target}</h1>}
/>;
const ComponentWhoseCodeCanBeReused = ({ render }) => {
const myData = {};
// reusable logic
return render(myData);
};

Did you notice that render prop is nothing but a function which we are calling from ComponentWhoseCodeCanBeReused component with some data.

The above code could be written like

<ComponentWhichCodeCanBeReused>
{(data) => <h1>Hello {data.target}</h1>}
</ComponentWhichCodeCanBeReused>;
const ComponentWhoseCodeCanBeReused = ({ children }) => {
const myData = {};
// reusable logic
return children(myData);
};

If you noticed that, the children prop is nothing but a function.

This is the render prop pattern. The name render prop comes from the concept of passing render prop to component which is a function. Like

render={(data) => <h1>Hello {data.target}</h1>}

Example

<Route path="/page" render={(props) => <Page {...props} data={extraProps} />} />

Thanks!

MIT © Mohan Dere.
-