Home » Reactjs » Call child method from parent

Call child method from parent

Posted by: admin November 29, 2017 Leave a comment

Questions:

I have two components.

  1. Parent component
  2. Child component

I was trying to call child’s method from Parent, I tried this way but couldn’t get a result

    class Parent extends Component {
     render() {
      return (
        <Child />
        <button onClick={Child.getAlert()}>Click</button>
      );
     }
    }

    class Child extends Component {
     getAlert() {
        alert('clicked');
     }
     render() {
      return (
        <h1 ref="hello">Hello</h1>
      );
     }
    }

Is there a way to call child’s method from the parent ?

Note: Child and Parent components are in two different files

Answers:

You can use refs.

class Parent extends Component {
 render() {
  return (
    <div>
      <Child ref="child" />
      <button onClick={() => this.refs.child.getAlert()}>Click</button>
    </div>
  );
 }
}

class Child extends Component {
 getAlert() {
    alert('clicked');
 }
 render() {
  return (
    <h1>Hello</h1>
  );
 }
}

Demonstration here


Edit

String refs are probably going to be deprecated in the future, so here’s how you’d do it with callback refs:

const { Component } = React;
const { render } = ReactDOM;

class Parent extends Component {
  render() {
    return (
      <div>
        <Child ref={instance => { this.child = instance; }} />
        <button onClick={() => { this.child.getAlert(); }}>Click</button>
      </div>
    );
  }
}

class Child extends Component {
  getAlert() {
    alert('clicked');
  }

  render() {
    return (
      <h1>Hello</h1>
    );
  }
}


render(
  <Parent />,
  document.getElementById('app')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="app"></div>

Questions:
Answers:

https://facebook.github.io/react/tips/expose-component-functions.html
for more answers ref here Call methods on React children components

By looking into the refs of the “reason” component, you’re breaking encapsulation and making it impossible to refactor that component without carefully examining all the places it’s used. Because of this, we strongly recommend treating refs as private to a component, much like state.

In general, data should be passed down the tree via props. There are a few exceptions to this (such as calling .focus() or triggering a one-time animation that doesn’t really “change” the state) but any time you’re exposing a method called “set”, props are usually a better choice. Try to make it so that the inner input component worries about its size and appearance so that none of its ancestors do.

Questions:
Answers:

You can use another pattern here:

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

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

What it does is to set the parent’s clickChild method when child is mounted. In this way when you click the button in parent it will call clickChild which calls child’s getAlert.

This also works if your child is wrapped with connect() so you don’t need the getWrappedInstance() hack.

Note 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.

Leave a Reply

Your email address will not be published. Required fields are marked *