Important Update
The Guide Feature will be discontinued after December 15th, 2023. Until then, you can continue to access and refer to the existing guides.
Author avatar

Gaurav Singhal

How to Reference a Function in Another Component

Gaurav Singhal

  • Mar 18, 2020
  • 9 Min read
  • 210,042 Views
  • Mar 18, 2020
  • 9 Min read
  • 210,042 Views
Web Development
Front End Web Development
Client-side Framework
React

Introduction

Components are an integral part of React. Each React application consists of several components, and each component may require user interaction that triggers various actions.

To achieve user interactivity, we can call functions and methods to accomplish specific operations in React. We pass data from parent to child or child to parent components using these actions.

Pass Action or Function to Child Component

You can pass state values to a child component as a prop, but you can also pass functions directly to the child component like this:

1<ChildComponent
2    // The child component will access using actionName
3    actionName={this.actual_action_name}
4/>
jsx

actionName is the name of the props that can be accessed by the child component. Once you trigger an action or pass the data from the child component, the same action's name will be accessed using this.props.action_name.

Let’s look at a simple example of passing an action to the child component.

1<MyChildComponent
2    onSubmitData={this.onSubmitData}
3/>
jsx

From the child component, you can trigger an action using this.props.onSubmitData() so that the action into the parent component will be triggered.

Pass Data from Child to Parent using Referenced Action

Props are one way to pass read-only data between components, and the actions are identical to the actual communication between the components.

You can pass the event handler to the component as a prop just as you would pass data such as string, number, array, objects, JSON, and so on.

But to pass data from a child component to a parent using an event handler, pass the data as a parameter. Let’s look at an example to elaborate more on this.

Example

This example implements a straightforward page with two text inputs and one button. Clicking the button triggers an action from the child component to access the action of the parent (as a prop).

The first step is to create the action in the parent component like this:

1constructor() {
2    super();
3    this.state = {
4    };
5    this.submitForm = this.submitForm.bind(this);
6}
7
8submitForm(values) {
9    this.setState({ values })
10}
jsx

The action is submitForm(). Use the same action to pass to the child component, like this:

1<FormDemo 
2    onFormSubmit={this.submitForm}
3/>
jsx

Now create the child component with the simple form, and based on the button click, access the action coming from the parent component, which is called onSubmitForm().

1import React, { Component } from "react";
2
3class FormDemo extends Component {
4  constructor() {
5    super();
6    this.state = {
7    };
8    this.onInputChange = this.onInputChange.bind(this);
9    this.onSubmitForm = this.onSubmitForm.bind(this);
10  }
11
12  onInputChange(event) {
13    this.setState({
14      [event.target.name]: event.target.value
15    });
16  }
17
18  onSubmitForm() {
19    this.props.onFormSubmit(this.state)
20  }
21
22  render() {
23    return (
24      <div>
25        <table>
26          <tr>
27            <td>First Name :</td>
28            <td>
29              <input type="text" name="fname" onChange={this.onInputChange} />
30            </td>
31          </tr>
32          <tr>
33            <td>Last Name :</td>
34            <td>
35              <input type="text" name="lname" onChange={this.onInputChange} />
36            </td>
37          </tr>
38          <tr>
39            <td>
40              <button onClick={this.onSubmitForm}>Submit</button>
41            </td>
42          </tr>
43        </table>
44      </div>
45    );
46  }
47}
48
49export default FormDemo;
jsx

This example has created two different actions. One is onInputChange(), which is used to update the state value once the input value has changed. The other is onSubmitForm(), which submits the form when the button is clicked.

The form body contains a table with the different inputs and button to submit the form, but note how to access the action from the parent component and pass the data to the child component.

1onSubmitForm() {
2    this.props.onFormSubmit(this.state)
3}
jsx

The above method triggers when the button is clicked, and the function accesses the method coming from the parent component as props called onFormSubmit().

So as soon as a user clicks the submit button, the updated values will be sent to the parent component.

Now, access the data coming from the child component to the parent component, like this:

1import React, { Component } from "react";
2import { render } from "react-dom";
3import FormDemo from "./FormDemo";
4
5class App extends Component {
6  constructor() {
7    super();
8    this.state = {
9    };
10    this.submitForm = this.submitForm.bind(this);
11  }
12
13  submitForm(values) {
14    this.setState({ values })
15  }
16
17  render() {
18    const { values } = this.state;
19
20    return (
21      <div>
22        <h2>Passing function to the child component</h2>
23        <hr />
24        <FormDemo 
25          onFormSubmit={this.submitForm}
26        /> <hr/>
27        <div>
28          Submitted form values : <br/>
29          First name: {values && values.fname} <br/>
30          Last name: {values && values.lname}
31        </div>
32      </div>
33    );
34  }
35}
36
37render(<App />, document.getElementById("root"));
jsx

In this parent component, get the values sent by the child component, like this:

1submitForm(values) {
2    this.setState({ values })
3}
jsx

From the function parameter, get the form values like fname and lname, which are sent by the child component as a callback data. Use it to render, like this:

1render() {
2    const { values } = this.state;
3
4    return (
5      <div>
6        <h2>Passing function to the child component</h2>
7        <hr />
8        <FormDemo 
9          onFormSubmit={this.submitForm}
10        /> <hr/>
11        <div>
12          Submitted form values : <br/>
13          First name: {values && values.fname} <br/>
14          Last name: {values && values.lname}
15        </div>
16      </div>
17    );
18  }
jsx

The render() function accessed the data coming from the child component and stored it into the local component state.

After storing the values to the state, you can access it by its name, like this:

1<div>
2    Submitted form values : <br/>
3    First name: {values && values.fname} <br/>
4    Last name: {values && values.lname}
5</div>
jsx

You have access to state values using values.fname and values.lname, which are coming from the child component.

This is not the only way to do this. You can also access the function directly from the click event without passing the reference to another function in the component.

1<tr>
2    <td>
3        <button onClick={() => this.props.onFormSubmit(this.state)}>Submit</button>
4    </td>
5</tr>
jsx

The above example shows how to access the function from the props directly using the onClick event. This is the other way to access the function directly from the element.

Apart from the above examples, you can also pass the value directly along with the function as a parameter. Once you access the function referenced from the parent, you can pass the value as a parameter, like this:

1<tr>
2    <td>
3        <button onClick={
4        () => this.props.onFormSubmit({
5            userName: 'Test123',
6            password: '123456'
7        })
8        }>
9            Submit
10        </button>
11    </td>
12</tr>
jsx

In this example, along with the function that is coming from the parent component called onFormSubmit(), the additional argument is provided as an object that contains the username and password.

This is how to pass arguments as objects, arrays, or JSON along with a function to the referenced function coming from the parent component.

Conclusion

In this guide, we have learned how to communicate between the components—more specifically, from a child component to a parent component—using the action handlers as props.

Passing child data using the reference in another component is one of the fundamental ways to communicate between components. I hope this guide was useful to you. Keep reading.

Learn More

Explore these React courses from Pluralsight to continue learning: