How to call instance methods of a child component?

Viewed 350

It's trivial to pass callback functions as props to child components, but not vice versa.

How do we call instance methods of a child component?

From <Parent /> component, I need to call this.bar instance method of <Child /> component.

class Parent extends React.Component {
    render() {
        return (
            <Child />
        )
    }
}

class Child extends React.Component {
    constructor( props ) {
        super( props );
        this.bar = () => console.log('foo');

    }

}
1 Answers

You can use refs to do that.

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.childRef = React.createRef();
  }

  componentDidMount() {
    this.childRef.current.bar()
  }

  render() {
    return (
      <Child ref={this.childRef} />
    );
  }
}

class Child extends React.Component {
  constructor( props ) {
    super( props );
    this.bar = () => console.log('foo');
  }

  render() {
    return <p>Child</p>
  }
}

Check out the Refs documentation

Related