DEV Community

Cover image for React call child function in parent
Chetan Rohilla
Chetan Rohilla

Posted on • Edited on • Originally published at w3courses.org

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>
  );
 }
}
Enter fullscreen mode Exit fullscreen mode

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.

Please like, share and give positive feedback to motivate me to write more.

Thanks:)
Happy Coding:)

Top comments (1)

Collapse
 
tranlehaiquan profile image
Q.Tran

And any reason why I do this?