React call child function in parent

In this tutorial we learn how react call child function in parent. We can do this easily by passing methods as props from parent component to child components. Then using props in react child component to access the passed properties.

How to call child function in parent in react

class Parent extends Component {
 render() {
  return (
    <div>
      <Child setClick={click => this.clickChild = click}/>
      <button onClick={() => this.clickChild()}>Click</button>
    </div>
  );
 }
}

class Child extends Component {
 constructor(props) {
    super(props);
    this.getAlert = this.getAlert.bind(this);
 }
 componentDidMount() {
    this.props.setClick(this.getAlert);
 }
 getAlert() {
    alert('clicked');
 }
 render() {
  return (
    <h1 ref="hello">Hello</h1>
  );
 }
}

Please Note that you can’t use onClick={this.clickChild} in parent because when parent is rendered child is not mounted so this.clickChild is not assigned yet. Using onClick={() => this.clickChild()} is fine because when you click the button this.clickChild should already be assigned.

Recommendation

How to validate form in ReactJS

How to create charts in ReactJS

How to call methods on browser resize in React

How to detect click outside of component in React

For more ReactJS Tutorials Click here.

If you like this, share this.

Follow us on FacebookTwitterTumblrLinkedInYouTube.