Author avatar

Gaurav Singhal

How to Pass a JSON Object from Child Component to Parent Component in React

Gaurav Singhal

  • Mar 23, 2020
  • 12 Min read
  • 31,863 Views
  • Mar 23, 2020
  • 12 Min read
  • 31,863 Views
Web Development
Front End Web Development
Client-side Framework
React

Introduction

Passing data between components is a crucial task for communication between components in React. State and props are the most widely used techniques for this. With state and props, you can pass several data types, including string, array, number, and object.

In this guide, you will learn how to pass data from a parent component to a child component and vice versa using different approaches including using props and state.

Passing Data from Parent to Child Component

React follows component-based architecture. Each screen, or a portion of the screen, can be represented by a component.

For example, static values can be passed to a child component like this:

1import React, { Component } from "react";
2import { render } from "react-dom";
3import Demo1 from "./demo1";
4
5class App extends Component {
6  constructor() {
7    super();
8    this.state = {
9      message: "This is dummy message",
10    };
11  }
12
13  render() {
14    const { message } = this.state;
15
16    return (
17      <div>
18        <div>Pass data from parent to child component</div>
19        <hr />
20        <Demo1 
21          message={this.state.message}
22        />
23      </div>
24    );
25  }
26}
27
28render(<App />, document.getElementById("root"));
jsx

Here in this app component, we have created one state value called message that contains text. To pass the same state value to the child component, called Demo1, create an additional key called message. Along with the key, pass the state value, like this.state.message, which can be consumed by the child component as a props value, like this:

1import React, { Component } from "react";
2
3class Demo1 extends Component {
4  constructor() {
5    super();
6    this.state = {
7      name: "React"
8    };
9  }
10
11  render() {
12    const { message } = this.props;
13
14    return (
15      <div>
16        <p>Data coming from parent component</p>
17        <hr />
18        <table>
19            <tr>
20              <td>Message is : { message }</td>
21            </tr>
22        </table>
23      </div>
24    );
25  }
26}
27
28export default Demo1;
jsx

You have accessed the props value by using the statement.

1const { message } = this.props;
jsx

And if you want to use it into the render() method, consume it by using its name directly, like this.

1<table>
2    <tr>
3        <td>Message is : { message }</td>
4    </tr>
5</table>
jsx

You have now accessed the value from the parent component to the child component. In the same way, you can also pass other values, like object or array, as explained below.

For example, if there is one array of employee and you have to show all the employee details into the child component, then pass the complete array like this:

1import React, { Component } from "react";
2import { render } from "react-dom";
3import Demo1 from "./demo1";
4
5class App extends Component {
6  constructor() {
7    super();
8    this.state = {
9      message: [],
10      employee: [
11        {
12          id: 1,
13          name: "Abc",
14          age: 25
15        },
16        {
17          id: 2,
18          name: "Def",
19          age: 28
20        },
21        {
22          id: 3,
23          name: "Ghi",
24          age: 30
25        }
26      ]
27    };
28    this.onSubmitMessage = this.onSubmitMessage.bind(this);
29  }
30
31  onSubmitMessage(message) {
32    this.setState({ message: message });
33  }
34
35  render() {
36    const { employee, message } = this.state;
37
38    return (
39      <div>
40        <div>Pass data from parent to child component</div>
41        <hr />
42        <Demo1 employeeData={employee} />
43      </div>
44    );
45  }
46}
47
48render(<App />, document.getElementById("root"));
jsx

Here in this example, you've passed one array, employee, into the state. employee contains different objects, including employee details, and based on the records, you'll need to show the details into the child component, but as a prop.

After passing the state values to the child component, access them from the child component like this:

1render() {
2    const { employeeData } = this.props;
3
4    return (
5      <div>
6        <p>Data coming from parent component</p>
7        <hr />
8        <table border="2">
9          {employeeData.map((data, index) => {
10            return (
11              <>
12                <tr key={data.id}>
13                  <td>id :</td>
14                  <td>{data.id}</td>
15                </tr>
16                <tr key={index}>
17                  <td>Name :</td>
18                  <td>{data.name}</td>
19                </tr>
20                <tr key={index}>
21                  <td>Age :</td>
22                  <td>{data.age}</td>
23                </tr>
24              </>
25            );
26          })}
27        </table>
28      </div>
29    );
30  }
jsx

Each record coming from the props sent by the parent component as props is called employeeData. This is one of the primary ways to send the data from a parent to a child component.

Passing JSON Objects from Child to Parent Component

It's important to is to implement the callback function so that once any action triggers the child component, it will then carry forwarded to the parent component.

Let’s look at one example of implementing a simple form that passes the message as text input driven by the form control, like this:

1import React, { Component } from "react";
2
3class Demo2 extends Component {
4  constructor() {
5    super();
6    this.state = {
7      greetingMessag: "",
8    };
9    this.onMessageChange = this.onMessageChange.bind(this);
10    this.onSubmit = this.onSubmit.bind(this);
11  }
12
13  onMessageChange(event) {
14    let message = event.target.value;
15    this.setState({ greetingMessag: message });
16  }
17
18  // pass message to parent component using callback
19  onSubmit() {
20    this.props.onSubmitMessage(this.state.greetingMessag);
21  }
22
23  render() {
24    return (
25      <div>
26        <p>Pass data from child component to parent</p>
27        <tr />
28        <table border="2">
29          <tr>
30            <td colspan="2">Pass greeting message to parent component</td>
31          </tr>
32          <tr>
33            <td>Type greeting message :</td>
34            <td>
35              <input type="text" onChange={this.onMessageChange} />
36            </td>
37          </tr>
38          <tr>
39            <td colspan="2">
40              <button onClick={this.onSubmit}>Submit</button>
41            </td>
42          </tr>
43        </table>
44      </div>
45    );
46  }
47}
48
49export default Demo2;
jsx

Let me explain this example.

  • We have one state value, greetingMessage, which can be updated once the user changes the input value and can send it to the parent component .
  • Then, there are two different methods. One is onMessageChange(), which is used to update the state value when a user changes the input value, and the other is onSubmit(), which is used to pass the updated message to the parent component as a callback function.
  • There is one form implemented that contains the input control and the button to submit the form as soon as a user clicks the submit button.

The main part is the onSubmit() method, which gets the method as a prop and passes down the updated message to the parent component.

1onSubmit() {
2    this.props.onSubmitMessage(this.state.greetingMessag);
3}
jsx

So after passing the updated message to the parent component, consume it into the parent component, like this:

1import React, { Component } from "react";
2import { render } from "react-dom";
3import Demo2 from "./demo2";
4
5class App extends Component {
6  constructor() {
7    super();
8    this.state = {
9      message: "",
10    };
11    this.onSubmitMessage = this.onSubmitMessage.bind(this);
12  }
13
14  onSubmitMessage(message) {
15    this.setState({ message: message });
16  }
17
18  render() {
19    const { employee, message } = this.state;
20
21    return (
22      <div>
23        <div>Pass data from parent to child component</div>
24        <div>
25            The message coming from the child component is : {message}
26        </div>
27        <hr />
28        <Demo2 
29          // passing as callback function
30          onSubmitMessage={this.onSubmitMessage} 
31        />
32      </div>
33    );
34  }
35}
36
37render(<App />, document.getElementById("root"));
jsx

In the above example, you have implemented the callback function.

1onSubmitMessage(message) {
2    this.setState({ message: message });
3}
jsx

So as soon as the user clicks on the submit button from the child component, the page will be redirected to the parent component, and you can use it based on your feasibility.

After getting the message from the child component as an argument from the function onSubmitMessage, configure it into the state value and consume it like this:

1render() {
2    const { employee, message } = this.state;
3
4    return (
5      <div>
6        <div>Pass data from parent to child component</div>
7        <div>
8            The message coming from the child component is : {message}
9        </div>
10        <hr />
11        <Demo2 
12          // passing as callback function
13          onSubmitMessage={this.onSubmitMessage} 
14        />
15      </div>
16    );
17  }
jsx

In the same way, pass the JSON object from child to parent component just as you would with normal values like text, number, array, object, and so on.

Create the JSON data into the state from the parent component, like this:

1constructor() {
2    super();
3    this.state = {
4      jsonData: [
5        {
6          id: 1,
7          name: "This is test1"
8        },
9        {
10          id: 2,
11          name: "This is test2"
12        },
13        {
14          id: 3,
15          name: "This is test3"
16        }
17      ]
18    };
19    this.onSubmit = this.onSubmit.bind(this);
20  }
jsx

The new JSON data, jsonData, is created, and you can pass it as callback data from the function once you trigger the callback function, like this:

1  onSubmit() {
2    this.props.onSubmitMessage(this.state.jsonData);
3  }
jsx

Now, consume the JSON data into the parent component, like this:

1onSubmitMessage(message) {
2    this.setState({ message: message });
3}
jsx

This is the method from the parent component, which can be triggered when the user clicks on the submit button from the child component. Afterward, you can consume the whole JSON object like this:

1render() {
2    const {  message } = this.state;
3
4    return (
5      <div>
6        <div>Pass data from parent to child component</div>
7        <div>
8          <table>
9            {message.map(item => {
10              return (
11                <tr>
12                  <td>{item.id} : </td>
13                  <td>{item.name}</td>
14                </tr>
15              );
16            })}
17          </table>
18        </div>
19        <hr />
20        <Demo2 onSubmitMessage={this.onSubmitMessage} />
21      </div>
22    );
23  }
jsx

Notice that the complete JSON object is being mapped in the render() function, which maps the different objects from the JSON data.

Conclusion

In this guide, you have learned how to pass data from a parent component to a child component and vice versa.

React supports component-based architecture; hence, we can pass various types of data between components, such as string, number, arrays, objects, or JSON based. I hope this guide helped you to learn about component communication. Stay tuned for more upcoming guides.