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.
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.
1import React, { Component } from "react";
2
3class App extends Component {
4 render() {
5 return (
6 <div>
7 <Hello name="John" />
8 </div>
9 );
10 }
11}
12
13const 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
.
1import React, { Component } from "react";
2
3class App extends Component {
4 constructor(props) {
5 super(props);
6 this.state = {
7 user: {
8 id: 12,
9 firstName: "John",
10 lastName: "Doe",
11 },
12 };
13 }
14 render() {
15 return (
16 <div>
17 <Account user={this.state.user} />
18 </div>
19 );
20 }
21}
22
23const Account = (props) => {
24 const { user } = props; // same as -> const user = props.user;
25 return (
26 <div>
27 <span>
28 Name - {user.firstName} {user.lastName}
29 </span>
30 <span>ID - {user.id}</span>
31 </div>
32 );
33};
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.
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.
1const eventBus = {
2 on(event, callback) {
3 document.addEventListener(event, (e) => callback(e.detail));
4 },
5 dispatch(event, data) {
6 document.dispatchEvent(new CustomEvent(event, { detail: data }));
7 },
8 remove(event, callback) {
9 document.removeEventListener(event, callback);
10 },
11};
12
13export 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.
1import React, { Component } from "react";
2import eventBus from "./eventBus";
3
4class App extends Component {
5 constructor(props) {
6 super(props);
7 this.state = {
8 user: {
9 id: 12,
10 firstName: "John",
11 lastName: "Doe",
12 },
13 };
14 }
15
16 componentDidMount() {
17 eventBus.dispatch("userData", this.state.user);
18 }
19
20 render() {
21 return (
22 <div>
23 <Account />
24 </div>
25 );
26 }
27}
28
29class Account extends Component {
30 constructor(props) {
31 super(props);
32 this.state = {
33 user: {},
34 };
35 }
36
37 componentDidMount() {
38 eventBus.on("userData", (user) => {
39 this.setState({ user });
40 });
41 }
42
43 render() {
44 const { user } = this.state; // same as -> const user = props.user;
45 return (
46 <div>
47 <span>
48 Name - {user.firstName} {user.lastName}
49 </span>
50 <span>ID - {user.id}</span>
51 </div>
52 );
53 }
54}
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.