Author avatar

Deeksha Sharma

Load and Render JSON Data into React Components

Deeksha Sharma

  • Apr 29, 2020
  • 12 Min read
  • 286,727 Views
  • Apr 29, 2020
  • 12 Min read
  • 286,727 Views
Web Development Front End
Web Development
Client-side Framework
React

Introduction

When building applications in React, we often need to work with JSON data. This data could come from third party APIs or be read from external files. In this guide, we will work on a code example to load the JSON data from a file and render it inside a React component.

Use Case

Say you have a data set in JSON format containing information on financial stocks from multiple companies. Each stock has metadata associated with it. Your goal is to read that data from an external file and render it on the web page in a tabular format, as shown below.

Stock Tracker

Set Up React App

Open your terminal and run these commands to use Create React App to get a sample app running on your machine.

1npx create-react-app load-json-data
2
3cd load-json-data
4
5yarn start
sh

Now, to run the app in the development mode, open http://localhost:3000 in your browser. You should see the sample app running with a React logo.

Add JSON Data to a File

Create a file in your project at location src/data.js and add the data below in your data.js file.

1export const stockData = [
2  {
3    company: "Twitter Inc",
4    ticker: "TWTR",
5    stockPrice: "22.76 USD",
6    timeElapsed: "5 sec ago",
7  },
8  {
9    company: "Square Inc",
10    ticker: "SQ",
11    stockPrice: "45.28 USD",
12    timeElapsed: "10 sec ago",
13  },
14  {
15    company: "Shopify Inc",
16    ticker: "SHOP",
17    stockPrice: "341.79 USD",
18    timeElapsed: "3 sec ago",
19  },
20  {
21    company: "Sunrun Inc",
22    ticker: "RUN",
23    stockPrice: "9.87 USD",
24    timeElapsed: "4 sec ago",
25  },
26  {
27    company: "Adobe Inc",
28    ticker: "ADBE",
29    stockPrice: "300.99 USD",
30    timeElapsed: "10 sec ago",
31  },
32  {
33    company: "HubSpot Inc",
34    ticker: "HUBS",
35    stockPrice: "115.22 USD",
36    timeElapsed: "12 sec ago",
37  },
38];
js

stockData is a JSON array containing dummy stock prices of some companies. Each JSON object inside this array contains four things:

  • Name of the company
  • Stock ticker for the company
  • Price of its stock
  • Last updated time in seconds

Using export const allows you to define and initialize variables that can be imported into any React component. In fact, you'll shortly import stockData as a JavaScript object in the next step.

Update App Component

It's time to update our <App> component because we need to render JSON data into our components. So head to the src/App.js file and remove all the boilerplate code that came with it. Instead, add this piece of code to the <App> component.

1import React from "react";
2import "./App.css";
3import { Stocks } from "./Stocks";
4
5function App() {
6  return (
7    <div className="App">
8      <Stocks />
9    </div>
10  );
11}
12
13export default App;
js

Go to the browser and open http://localhost:3000. You will see errors in the application because the <App/> component wraps and returns a <Stocks/> component that doesn't exist yet. Don't worry—you will add this new component next.

Create Stocks Component

You will now add a new component inside the src directory and name it Stocks.js. The location of the <Stocks/> component inside your project should be src/Stocks.js. Add the code below to your <Stocks> component file. The code currently doesn't do anything except return a <div> containing the message Welcome to Stock Tracker, but you will extend this code shortly.

1import React from "react";
2import "./App.css";
3
4export const Stocks = () => {
5  return (
6    <>
7      <div className="stock-container">Welcome to Stock Tracker</div>
8    </>
9  );
10};
js

Add the css class stock-container inside src/App.css file. The code inside the App.css file should look like this.

1.App {
2  text-align: center;
3}
4
5.stock-container {
6  padding-left: 3em;
7  padding-right: 3em;
8  margin-top: 3em;
9}
css

Go to the browser and open http://localhost:3000. You should see the message Welcome to Stock Tracker rendered on your web page, and there should not be any errors.

Load JSON Data into Stocks Component

Now that your <Stocks> component is ready, you can get the JSON data from the src/data.js file and render it inside <Stocks>. React allows using named imports, and we can leverage that to load JSON data. So go ahead and add this import in your src/Stocks.js file.

1import { stockData } from "./data";
js

The next task is to iterate over the stockData array imported from the data.js file. Inside your <Stocks> component, add the logic to go over every element from the stockData array.

1import React from "react";
2import "./App.css";
3import { stockData } from "./data";
4
5export const Stocks = () => {
6  return (
7    <>
8      <div className="stock-container">
9        {stockData.map((data, key) => {
10          return (
11            <div key={key}>
12              {data.company +
13                " , " +
14                data.ticker +
15                " ," +
16                data.stockPrice +
17                ", " +
18                data.timeElapsed}
19            </div>
20          );
21        })}
22      </div>
23    </>
24  );
25};
js

Let's unpack what the above code does. It maps over the stockData JSON array, which takes a callback function as argument. This function is then called for every stock inside the stockData array. Each time callback executes, it returns and renders a <div> displaying data for every company in a comma separated manner.

Go to the browser and open http://localhost:3000. The data for all stocks should be rendered in rows on the web page. You'll render this in a tabular format in the next step. But for now, you should see all your JSON data.

Display Stock Information In a Tabular Format

The last piece of work is to render that data in a component. There are a few of changes we need to make:

  1. Add a <HomePageHeader> component to display a header.
  2. Add a <Stock> component that accepta data in props and renders a table on the web page.
  3. Refactor the code inside the <Stocks> component to accommodate the above two changes.

Add this piece of code for the <HomePageHeader> component inside the src/Stocks.js file.

1const HomePageHeader = () => {
2  return (
3    <header className="header">
4      <h2>Your Stock Tracker</h2>
5    </header>
6  );
7};
js

The <HomePageHeader> component also uses a CSS class header, so we need to add it inside src/App.css.

1.header {
2  background-color: #f4e04d;
3  min-height: 10vh;
4  display: flex;
5  flex-direction: column;
6  align-items: center;
7  justify-content: center;
8  font-size: calc(10px + 2vmin);
9  color: #10375c;
10}
css

The next task is to create a <Stock> component so you can abstract your code to render each stock separately. Go ahead and add this code for the <Stock> component inside your src/Stocks.js file.

1```js
2const Stock = ({ company, ticker, stockPrice, timeElapsed }) => {
3  if (!company) return <div />;
4  return (
5    <table>
6      <tbody>
7        <tr>
8          <td>
9            <h5>{company}</h5>
10          </td>
11          <td>
12            <h5>{ticker}</h5>
13          </td>
14          <td>
15            <h4>{stockPrice}</h4>
16          </td>
17          <td>
18            <p>{timeElapsed}</p>
19          </td>
20        </tr>
21      </tbody>
22    </table>
23  );
24};
25```

This component accepts props and returns an HTML table for a stock with four columns rendering the company name, ticker, stock price, and time elapsed in seconds.

Next, do some styling for the table. To do so, you'll need the css code in hte src/App.css file.

1```css
2table {
3  display: flex;
4  justify-content: center;
5  border: 1px solid gray;
6}
7td {
8  border: 1px solid gray;
9  width: 30em;
10}
11```

Finally, refactor the <Stocks> component so it can call the <HomePageHeader> and <Stock> components we just created. The code below renders the <Stocks> component containing a <HomePageHeader> and <Stock> for every element in inside the stockData array. Instead of displaying the JSON data inside a div, you'll now pass it as props to <Stock> component.

1```js
2export const Stocks = () => {
3  return (
4    <>
5      <HomePageHeader />
6      <div className="stock-container">
7        {stockData.map((data, key) => {
8          return (
9            <div key={key}>
10              <Stock
11                key={key}
12                company={data.company}
13                ticker={data.ticker}
14                stockPrice={data.stockPrice}
15                timeElapsed={data.timeElapsed}
16              />
17            </div>
18          );
19        })}
20      </div>
21    </>
22  );
23};
24```

Make sure your src/Stocks.js looks exactly like this before you view the webpage in your browser.

1```js
2import React from "react";
3import "./App.css";
4import { stockData } from "./data";
5
6export const Stocks = () => {
7  return (
8    <>
9      <HomePageHeader />
10      <div className="stock-container">
11        {stockData.map((data, key) => {
12          return (
13            <div key={key}>
14              <Stock
15                key={key}
16                company={data.company}
17                ticker={data.ticker}
18                stockPrice={data.stockPrice}
19                timeElapsed={data.timeElapsed}
20              />
21            </div>
22          );
23        })}
24      </div>
25    </>
26  );
27};
28
29const HomePageHeader = () => {
30  return (
31    <header className="header">
32      <h2>Your Stock Tracker</h2>
33    </header>
34  );
35};
36
37const Stock = ({ company, ticker, stockPrice, timeElapsed }) => {
38  if (!company) return <div />;
39  return (
40    <table>
41      <tbody>
42        <tr>
43          <td>
44            <h5>{company}</h5>
45          </td>
46          <td>
47            <h5>{ticker}</h5>
48          </td>
49          <td>
50            <h4>{stockPrice}</h4>
51          </td>
52          <td>
53            <p>{timeElapsed}</p>
54          </td>
55        </tr>
56      </tbody>
57    </table>
58  );
59};
60```

Go to the browser and open http://localhost:3000. You should be able to see the JSON data sourced from an external file displayed in a tabular format.

Access Code on Github

The code for this application is available on Github.

Build and Deploy this Application

To build the app for production to the build folder, use yarn build on your terminal inside the root of the project. This correctly bundles React in production mode and optimizes the build for the best performance.

The build is minified and the filenames include the hashes. Your app is ready to be deployed!

Conclusion

This is one approach to loading JSON data into your React app. If your app is growing and the bundle is becoming large, you may want to consider using code splitting through dynamic imports, which improves performance of the app by loading only the code needed for initial load. Read more about Code Splitting in the React documentation.