Search code examples
javascriptreactjsinstancefunction-call

How can I call a function from one component to another? React


I'm working in react.js. I've created a component Backend.jsx. I want it to work as a service (like in angular) where I can send API requests. I want to call methods of Backend in some other components.

I called this backend service in component and try to send data and get it in BackendService using props.

But obviously this will not work.

Here's my code

In Component:

This will be called after form submit.

handleLoginSubmit = (event) => {
    event.preventDefault();
    console.log(this.state.data);
    <BackendService onSendData = {this.state.data} />
}

In BackendService:

constructor(props) {
    super(props);
    this.state = {  }
    this.login(props)
}
login = (props) =>
{
    console.log('login', props);
};

Any suggestions how can I call this login method in component. Or any other suggestion to get component data in service.


Solution

  • You can try this:

    1.Component.js

    class Componet extends React.Component {
      constructor(props) {
        super(props);
        this.state={
          data:"this state contain data"
        }
    
        this.backendServiceRef = React.createRef(); // Using this ref you can access method and state of backendService component.
      }
    
      render() {
        return (
          <div className="App">
            <button onClick={() => {
    
              this.backendServiceRef.current.login()  
    
           }}>click</button>
    
            <BackendService ref={this.backendServiceRef} onSendData = {this.state.data}></BackendService>
          </div>
        );
      }
    }
    
    export default Componet;  
    

    2.BackendService.js

    class BackendService extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
        }
      }
    
      login = (props) => {
        alert("login call")
      };
    
      render() {
        return (
          <div>
            Backend service component
          </div>
        )
      }
    }