This post is going to show that when a component is embedded as a ‘child’ component in another component, how that child component can invoke a function in the ‘parent’ component.

In this scenario, we are going to suppose that you have a very simple App.js component, which embeds a Signup component.

When the request from the Signup component is made by, let’s say, clicking a button, we want the Signup component to notify the App component and also pass in the data that the user has provided.

The App.js in this example is simple:

import React from 'react';
import Signup from './components/authentication/Signup';

class App extends React.Component {

  render() {
    return (
      <Signup/>
    );
  }
}

export default App;

We just have the embedded Signup Component.

Invoking the method

Now in the Signup component, in the button which submits the data, simply add the following:

<button onClick={this.props.signupRequest}>Submit</button>

Notice the use of this.props.signupRequest.

Now open App.js and update the Signup component invocation:

<Signup signupRequest={this.signupRequest}/>

And add a method with the name of this.signupRequest.

signupRequest = () => {
    console.log('Signup request invoked');
  }

Now whenever you click the button in the Signup component, the method inside the App component is going to invoke.

How to pass parameters from child component to parent component?

As the next step, you will want to pass in parameters from the Signup to the App component as well.

Open Signup.js and update the onClick command:

<button onClick={this.props.signupRequest.bind(this, 'Incoming')}>Submit</button>

Notice the bind, the first parameter this and your custom parameter.

Now open App.js and simply add a parameter to the signupRequest method:

signupRequest = (incomingParameter) => {
    console.log('Signup request invoked: ' + incomingParameter);
  }

You can pass in more complex objects as parameter but for the sake of example, this would do for now.