How to pass a function to a child component in React.

A woman holding the hand of her child outdoors, in a dry environment on a dusty trail, with a pond in the background. The woman and child have their backs facing us.

In React, passing a function to a child component can easily be done by passing the function as a prop to the child. This works even when the function uses state from the parent. If we bind the function with the keyword ‘this’ in it’s parent constructor, then we can freely use the function in the children of the parent component. For example:

class Game extends Component {
  constructor(props){
    super(props);
    this.state = {
      colors: ['red', 'yellow', 'blue']
    };
    this.onNext = this.onNext.bind(this); //Bind function to 'this'
  }
  onNext(){
    const {colors} = this.state; //function uses state from parent
  }
  render(){
    return( 
      <div>
        <Child
          nextGame={this.onNext} 
        />
      </div>
    )
  }
}

...

//Child component
function Child (nextGame) {
  return(
    <button onClick={nextGame}>Next Game</button> {/*Call nextGame on click*/}
  )
}

This simple method confused me, because I was thinking about the fact that you can’t access a parent’s state from a child without passing the parent’s state to the child via props. However, we are not accessing the parent’s state from the child. The function is being called from the child, but it is being evaluated in the context of the parent, so the function is not lacking state information.

Photo credit: @guillaumedegermain, Unsplash

Subscribe to new blog posts