Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

How to Reference a Function in Another Component

Mar 18, 2020 • 9 Minute Read

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:

      <ChildComponent
    // The child component will access using actionName
    actionName={this.actual_action_name}
/>
    

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.

      <MyChildComponent
    onSubmitData={this.onSubmitData}
/>
    

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:

      constructor() {
    super();
    this.state = {
    };
    this.submitForm = this.submitForm.bind(this);
}

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

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

      <FormDemo 
    onFormSubmit={this.submitForm}
/>
    

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().

      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;
    

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.

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

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:

      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"));
    

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

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

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:

      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>
    );
  }
    

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:

      <div>
    Submitted form values : <br/>
    First name: {values && values.fname} <br/>
    Last name: {values && values.lname}
</div>
    

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.

      <tr>
    <td>
        <button onClick={() => this.props.onFormSubmit(this.state)}>Submit</button>
    </td>
</tr>
    

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:

      <tr>
    <td>
        <button onClick={
        () => this.props.onFormSubmit({
            userName: 'Test123',
            password: '123456'
        })
        }>
            Submit
        </button>
    </td>
</tr>
    

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: