Skip to content

Contact sales

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

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

Mar 23, 2020 • 12 Minute Read

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:

      import React, { Component } from "react";
import { render } from "react-dom";
import Demo1 from "./demo1";

class App extends Component {
  constructor() {
    super();
    this.state = {
      message: "This is dummy message",
    };
  }

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

    return (
      <div>
        <div>Pass data from parent to child component</div>
        <hr />
        <Demo1 
          message={this.state.message}
        />
      </div>
    );
  }
}

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

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:

      import React, { Component } from "react";

class Demo1 extends Component {
  constructor() {
    super();
    this.state = {
      name: "React"
    };
  }

  render() {
    const { message } = this.props;

    return (
      <div>
        <p>Data coming from parent component</p>
        <hr />
        <table>
            <tr>
              <td>Message is : { message }</td>
            </tr>
        </table>
      </div>
    );
  }
}

export default Demo1;
    

You have accessed the props value by using the statement.

      const { message } = this.props;
    

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

      <table>
    <tr>
        <td>Message is : { message }</td>
    </tr>
</table>
    

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:

      import React, { Component } from "react";
import { render } from "react-dom";
import Demo1 from "./demo1";

class App extends Component {
  constructor() {
    super();
    this.state = {
      message: [],
      employee: [
        {
          id: 1,
          name: "Abc",
          age: 25
        },
        {
          id: 2,
          name: "Def",
          age: 28
        },
        {
          id: 3,
          name: "Ghi",
          age: 30
        }
      ]
    };
    this.onSubmitMessage = this.onSubmitMessage.bind(this);
  }

  onSubmitMessage(message) {
    this.setState({ message: message });
  }

  render() {
    const { employee, message } = this.state;

    return (
      <div>
        <div>Pass data from parent to child component</div>
        <hr />
        <Demo1 employeeData={employee} />
      </div>
    );
  }
}

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

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:

      render() {
    const { employeeData } = this.props;

    return (
      <div>
        <p>Data coming from parent component</p>
        <hr />
        <table border="2">
          {employeeData.map((data, index) => {
            return (
              <>
                <tr key={data.id}>
                  <td>id :</td>
                  <td>{data.id}</td>
                </tr>
                <tr key={index}>
                  <td>Name :</td>
                  <td>{data.name}</td>
                </tr>
                <tr key={index}>
                  <td>Age :</td>
                  <td>{data.age}</td>
                </tr>
              </>
            );
          })}
        </table>
      </div>
    );
  }
    

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:

      import React, { Component } from "react";

class Demo2 extends Component {
  constructor() {
    super();
    this.state = {
      greetingMessag: "",
    };
    this.onMessageChange = this.onMessageChange.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
  }

  onMessageChange(event) {
    let message = event.target.value;
    this.setState({ greetingMessag: message });
  }

  // pass message to parent component using callback
  onSubmit() {
    this.props.onSubmitMessage(this.state.greetingMessag);
  }

  render() {
    return (
      <div>
        <p>Pass data from child component to parent</p>
        <tr />
        <table border="2">
          <tr>
            <td colspan="2">Pass greeting message to parent component</td>
          </tr>
          <tr>
            <td>Type greeting message :</td>
            <td>
              <input type="text" onChange={this.onMessageChange} />
            </td>
          </tr>
          <tr>
            <td colspan="2">
              <button onClick={this.onSubmit}>Submit</button>
            </td>
          </tr>
        </table>
      </div>
    );
  }
}

export default Demo2;
    

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.

      onSubmit() {
    this.props.onSubmitMessage(this.state.greetingMessag);
}
    

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

      import React, { Component } from "react";
import { render } from "react-dom";
import Demo2 from "./demo2";

class App extends Component {
  constructor() {
    super();
    this.state = {
      message: "",
    };
    this.onSubmitMessage = this.onSubmitMessage.bind(this);
  }

  onSubmitMessage(message) {
    this.setState({ message: message });
  }

  render() {
    const { employee, message } = this.state;

    return (
      <div>
        <div>Pass data from parent to child component</div>
        <div>
            The message coming from the child component is : {message}
        </div>
        <hr />
        <Demo2 
          // passing as callback function
          onSubmitMessage={this.onSubmitMessage} 
        />
      </div>
    );
  }
}

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

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

      onSubmitMessage(message) {
    this.setState({ message: message });
}
    

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:

      render() {
    const { employee, message } = this.state;

    return (
      <div>
        <div>Pass data from parent to child component</div>
        <div>
            The message coming from the child component is : {message}
        </div>
        <hr />
        <Demo2 
          // passing as callback function
          onSubmitMessage={this.onSubmitMessage} 
        />
      </div>
    );
  }
    

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:

      constructor() {
    super();
    this.state = {
      jsonData: [
        {
          id: 1,
          name: "This is test1"
        },
        {
          id: 2,
          name: "This is test2"
        },
        {
          id: 3,
          name: "This is test3"
        }
      ]
    };
    this.onSubmit = this.onSubmit.bind(this);
  }
    

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:

      onSubmit() {
    this.props.onSubmitMessage(this.state.jsonData);
  }
    

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

      onSubmitMessage(message) {
    this.setState({ message: message });
}
    

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:

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

    return (
      <div>
        <div>Pass data from parent to child component</div>
        <div>
          <table>
            {message.map(item => {
              return (
                <tr>
                  <td>{item.id} : </td>
                  <td>{item.name}</td>
                </tr>
              );
            })}
          </table>
        </div>
        <hr />
        <Demo2 onSubmitMessage={this.onSubmitMessage} />
      </div>
    );
  }
    

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.

Gaurav Singhal

Gaurav S.

Guarav is a Data Scientist with a strong background in computer science and mathematics. He has extensive research experience in data structures, statistical data analysis, and mathematical modeling. With a solid background in Web development he works with Python, JAVA, Django, HTML, Struts, Hibernate, Vaadin, Web Scrapping, Angular, and React. His data science skills include Python, Matplotlib, Tensorflows, Pandas, Numpy, Keras, CNN, ANN, NLP, Recommenders, Predictive analysis. He has built systems that have used both basic machine learning algorithms and complex deep neural network. He has worked in many data science projects, some of them are product recommendation, user sentiments, twitter bots, information retrieval, predictive analysis, data mining, image segmentation, SVMs, RandomForest etc.

More about this author