/

React Render Props

React Render Props

Discover how Render Props can enhance your React application

One common approach to share state between components in React is through the use of the children prop.

In the JSX of a component, you can include {this.props.children}, which automatically injects any JSX passed in the parent component as children:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Parent extends React.Component {
constructor(props) {
super(props)
this.state = {
/*...*/
}
}

render() {
return <div>{this.props.children}</div>
}
}

const Children1 = () => {}

const Children2 = () => {}

const App = () => (
<Parent>
<Children1 />
<Children2 />
</Parent>
)

However, there’s a limitation here: the state of the parent component cannot be accessed from the children.

To overcome this limitation, you can use a render prop component. Rather than passing components as children of the parent component, you pass a function which can be executed using {this.props.children()}. The function can also accept arguments:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Parent extends React.Component {
constructor(props) {
super(props)
this.state = { name: 'Flavio' }
}

render() {
return <div>{this.props.children(this.state.name)}</div>
}
}

const Children1 = props => {
return <p>{props.name}</p>
}

const App = () => <Parent>{name => <Children1 name={name} />}</Parent>

Instead of using the children prop, which has a specific meaning, you can use any prop. This allows you to utilize this pattern multiple times within the same component:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Parent extends React.Component {
constructor(props) {
super(props)
this.state = { name: 'Flavio', age: 35 }
}

render() {
return (
<div>
<p>Test</p>
{this.props.someprop1(this.state.name)}
{this.props.someprop2(this.state.age)}
</div>
)
}
}

const Children1 = props => {
return <p>{props.name}</p>
}

const Children2 = props => {
return <p>{props.age}</p>
}

const App = () => (
<Parent
someprop1={name => <Children1 name={name} />}
someprop2={age => <Children2 age={age} />}
/>
)

ReactDOM.render(<App />, document.getElementById('app'))

Tags: React, Render Props, State Management