How to call a function from another component in react

In React, to call a function from another component, you need to follow a certain approach. Here’s an explanation with an example:

Let’s say you have two components – Component A and Component B. Component A has a function called myFunction that you want to call from Component B.

Step 1: Import Component A in Component B:

    
import ComponentA from './ComponentA';
    
  

Step 2: Create an instance of Component A in Component B:

    
const componentAInstance = new ComponentA();
    
  

Step 3: Call the function myFunction from Component A:

    
componentAInstance.myFunction();
    
  

Here’s a complete example:

ComponentA.js:

    
import React from 'react';

class ComponentA extends React.Component {
  myFunction() {
    console.log("Function called from Component A");
  }

  render() {
    return (
      <div>
        <h1>Component A</h1>
      </div>
    );
  }
}

export default ComponentA;
    
  

ComponentB.js:

    
import React from 'react';
import ComponentA from './ComponentA';

class ComponentB extends React.Component {
  callFunctionFromComponentA() {
    const componentAInstance = new ComponentA();
    componentAInstance.myFunction();
  }

  render() {
    return (
      <div>
        <h1>Component B</h1>
        <button onClick={this.callFunctionFromComponentA}>Call Function from Component A</button>
      </div>
    );
  }
}

export default ComponentB;
    
  

Leave a comment