Categories
React Answers

How to call a method from another class component in React.js?

Spread the love

To call a method from another class component in React.js, we pass the function from the parent component to the child as a prop.

Then we call the parent component’s method that we got from the prop.

For instance, we write

export class Class1 extends Component {
  render() {
    return <div onClick={this.props.callApi}></div>;
  }
}

to set onClick to this.props.callApi to call callApi when we click on the div.

Then we write

export class Class2 extends Component {
  callApi = () => {
    //...
  };

  render() {
    return <Class1 callApi={this.callApi} />;
  }
}

to add the Class2 component that renders Class1 and pass callApi to Class1 by setting the callApi prop to this.callApi.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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