Skip to content

Contact sales

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

How to Pass JSON Values into React Components

Jul 23, 2020 • 5 Minute Read

Introduction

When you were starting with React, you probably came across many examples of React apps with components that used shared data. These components are very simple in terms of complexity and are pretty easy to understand. However, when you are working on a production-level app, you will notice that the data comes from many different sources and services.

It is vital that the components you build are scalable, maintainable, and do not cause any bottleneck in the app. In this guide, you will learn how to pass JSON data to a component.

Passing Values Using Props

React components can access data from other components via props. Props are used to send data from one component to another.

In the below example, the Hello component accepts a name prop.

      import React, { Component } from "react";

class App extends Component {
  render() {
    return (
      <div>
        <Hello name="John" />
      </div>
    );
  }
}

const Hello = (props) => <h1>Hello {props.name}</h1>;
    

Similarly, JSON values can be passed inside the props.

Consider the following example. Here, a user is set in the state of the App component and passed as the user prop to the Account component. The Account component can access the value using props.user.

      import React, { Component } from "react";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      user: {
        id: 12,
        firstName: "John",
        lastName: "Doe",
      },
    };
  }
  render() {
    return (
      <div>
        <Account user={this.state.user} />
      </div>
    );
  }
}

const Account = (props) => {
  const { user } = props; // same as -> const user = props.user;
  return (
    <div>
      <span>
        Name - {user.firstName} {user.lastName}
      </span>
      <span>ID - {user.id}</span>
    </div>
  );
};
    

Generally, the JSON data comes from an external source, like an API or a JSON file, but for simplicity here it is added from the state. No matter how complex or large the JSON object is, it can still be passed using props. React does not have any limitations regarding the size of props.

Passing Values Using Events

In a previous guide, you learned how you could use an event bus to pass data between independent components that do not share any common functionality or features. Likewise, you can pass JSON data using the event bus.

Below you can find the code for the event bus, which was explained in greater detail in the earlier guide. To summarize here, the on method attaches an event to the document object, the dispatch method can fire an event along with some data, and the remove method can un-attach the event to prevent memory leakage.

      const eventBus = {
  on(event, callback) {
    document.addEventListener(event, (e) => callback(e.detail));
  },
  dispatch(event, data) {
    document.dispatchEvent(new CustomEvent(event, { detail: data }));
  },
  remove(event, callback) {
    document.removeEventListener(event, callback);
  },
};

export default eventBus;
    

Now, using the event bus, dispatch a userData event along with the user data from the state inside the componentDidMount() lifecycle method. In the Account component, listen to the userData event, and when the event is triggered, set the user data in the state.

Here you will notice that unlike the previous example, you did not have to pass the user data as a prop to the Account component.

      import React, { Component } from "react";
import eventBus from "./eventBus";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      user: {
        id: 12,
        firstName: "John",
        lastName: "Doe",
      },
    };
  }

  componentDidMount() {
    eventBus.dispatch("userData", this.state.user);
  }

  render() {
    return (
      <div>
        <Account />
      </div>
    );
  }
}

class Account extends Component {
  constructor(props) {
    super(props);
    this.state = {
      user: {},
    };
  }

  componentDidMount() {
    eventBus.on("userData", (user) => {
      this.setState({ user });
    });
  }

  render() {
    const { user } = this.state; // same as -> const user = props.user;
    return (
      <div>
        <span>
          Name - {user.firstName} {user.lastName}
        </span>
        <span>ID - {user.id}</span>
      </div>
    );
  }
}
    

Conclusion

To summarize, you can pass JSON data to other components using props or an event bus; which method to choose is for you to decide based on the requirements of your app. However, it is advised that you use props so that React can keep track of the data and communication between the components. Using an event bus in some cases might lead to unexpected results. Therefore, an event bus must only be used in case of interaction between independent components. That is it from this guide; until next time, stay safe and keep coding.