top of page
Logo der Online Agentur mdwp

Render Props

Render Props in React JS is a technique used for sharing code between React components using a prop whose value is a function. It is a pattern in which a component's children are a function that will be invoked with some arguments (often data) and should return a React element.

The main idea is to have a component that defines some behavior or data and exposes it via a prop. This prop can be rendered by the parent component and the state or functionality that is necessary can be passed via parameters. This leads to better code sharing and easier testing.

Here is a simple example where we pass a function via the "render" prop :

```jsx
class DataProvider extends React.Component {
state = { data: 'Hello' }

render() {
return this.props.render(this.state.data);
}
}

class MyComponent extends React.Component {
render() {
return (
<DataProvider render={data => (
<div>
Hello {data}!
</div>
)} />
);
}
}

```
In the above example, the DataProvider component maintains some state and uses this.props.render() to render it in the UI. The MyComponent component uses the DataProvider component and specifies how to render the DataProvider's state by passing a function via the render prop. The data from DataProvider's state is passed to this function and is then rendered in the <div> tag inside MyComponent.

The render props technique is a very powerful one and is occasionally used interchangeably with the concept of higher-order components. Both have their own use cases and slightly different advantages - but both aim at reusing component logic.

bottom of page