Categories
React Answers

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

Spread the love

Sometimes, we want to call a method from another class component in React.js.

In this article, we’ll look at how to call a method from another class component in React.js.

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

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

For instance, we write:

import React, { Component } from "react";

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

class Class2 extends Component {
  onClick = () => {
    console.log("class 2 click");
  };

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

export default function App() {
  return <Class2 />;
}

We have components Class1 and Class2.

And Class1 is a child of Class2.

To pass the onClick method as a prop to Class1, we add onClick={this.onClick}.

Then in Class1, we get the onClick method from this.props and set that as the value of the onClick prop of the div.

Now when we click on the div, we see 'class 2 click' logged.

Conclusion

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

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 *