Author avatar

Gaurav Singhal

How to Reference a Function in Another Component

Gaurav Singhal

  • Mar 18, 2020
  • 8 Min read
  • 14,229 Views
  • Mar 18, 2020
  • 8 Min read
  • 14,229 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
2
3
4
<ChildComponent
    // The child component will access using actionName
    actionName={this.actual_action_name}
/>
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
2
3
<MyChildComponent
    onSubmitData={this.onSubmitData}
/>
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:

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

submitForm(values) {
    this.setState({ values })
}
jsx

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

1
2
3
<FormDemo 
    onFormSubmit={this.submitForm}
/>
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().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import React, { Component } from "react";

class FormDemo extends Component {
  constructor() {
    super();
    this.state = {
    };
    this.onInputChange = this.onInputChange.bind(this);
    this.onSubmitForm = this.onSubmitForm.bind(this);
  }

  onInputChange(event) {
    this.setState({
      [event.target.name]: event.target.value
    });
  }

  onSubmitForm() {
    this.props.onFormSubmit(this.state)
  }

  render() {
    return (
      <div>
        <table>
          <tr>
            <td>First Name :</td>
            <td>
              <input type="text" name="fname" onChange={this.onInputChange} />
            </td>
          </tr>
          <tr>
            <td>Last Name :</td>
            <td>
              <input type="text" name="lname" onChange={this.onInputChange} />
            </td>
          </tr>
          <tr>
            <td>
              <button onClick={this.onSubmitForm}>Submit</button>
            </td>
          </tr>
        </table>
      </div>
    );
  }
}

export 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.

1
2
3
onSubmitForm() {
    this.props.onFormSubmit(this.state)
}
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import React, { Component } from "react";
import { render } from "react-dom";
import FormDemo from "./FormDemo";

class App extends Component {
  constructor() {
    super();
    this.state = {
    };
    this.submitForm = this.submitForm.bind(this);
  }

  submitForm(values) {
    this.setState({ values })
  }

  render() {
    const { values } = this.state;

    return (
      <div>
        <h2>Passing function to the child component</h2>
        <hr />
        <FormDemo 
          onFormSubmit={this.submitForm}
        /> <hr/>
        <div>
          Submitted form values : <br/>
          First name: {values && values.fname} <br/>
          Last name: {values && values.lname}
        </div>
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));
jsx

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

1
2
3
submitForm(values) {
    this.setState({ values })
}
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
render() {
    const { values } = this.state;

    return (
      <div>
        <h2>Passing function to the child component</h2>
        <hr />
        <FormDemo 
          onFormSubmit={this.submitForm}
        /> <hr/>
        <div>
          Submitted form values : <br/>
          First name: {values && values.fname} <br/>
          Last name: {values && values.lname}
        </div>
      </div>
    );
  }
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
2
3
4
5
<div>
    Submitted form values : <br/>
    First name: {values && values.fname} <br/>
    Last name: {values && values.lname}
</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
2
3
4
5
<tr>
    <td>
        <button onClick={() => this.props.onFormSubmit(this.state)}>Submit</button>
    </td>
</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
2
3
4
5
6
7
8
9
10
11
12
<tr>
    <td>
        <button onClick={
        () => this.props.onFormSubmit({
            userName: 'Test123',
            password: '123456'
        })
        }>
            Submit
        </button>
    </td>
</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.

17