DEV Community

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

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

4 2

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?

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay