React rendering props

Learn how rendering props can help you build React apps

The common pattern for sharing state between components is to usechildrenpillar.

In the component JSX, you can render{this.props.children}It will automatically inject all JSX passed in the parent component as child components:

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 is a problem here: the state of the parent component cannot be accessed from the child.

In order to be able to share state, you need to use the render prop component, instead of passing the component as a child of the parent component, but passing a function and then executing it in it{this.props.children()}. The function can accept parameters:

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 usingchildrenProp, it has a very special meaning, you can use any prop, so you can use this pattern multiple times on the same component:

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’))

Download mine for freeResponse Handbook


More response tutorials: