Load and Render JSON Data into React Components
Apr 29, 2020 • 12 Minute Read
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.
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.
npx create-react-app load-json-data
cd load-json-data
yarn start
Now, to run the app in the development mode, open https://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.
export const stockData = [
{
company: "Twitter Inc",
ticker: "TWTR",
stockPrice: "22.76 USD",
timeElapsed: "5 sec ago",
},
{
company: "Square Inc",
ticker: "SQ",
stockPrice: "45.28 USD",
timeElapsed: "10 sec ago",
},
{
company: "Shopify Inc",
ticker: "SHOP",
stockPrice: "341.79 USD",
timeElapsed: "3 sec ago",
},
{
company: "Sunrun Inc",
ticker: "RUN",
stockPrice: "9.87 USD",
timeElapsed: "4 sec ago",
},
{
company: "Adobe Inc",
ticker: "ADBE",
stockPrice: "300.99 USD",
timeElapsed: "10 sec ago",
},
{
company: "HubSpot Inc",
ticker: "HUBS",
stockPrice: "115.22 USD",
timeElapsed: "12 sec ago",
},
];
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.
import React from "react";
import "./App.css";
import { Stocks } from "./Stocks";
function App() {
return (
<div className="App">
<Stocks />
</div>
);
}
export default App;
Go to the browser and open https://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.
import React from "react";
import "./App.css";
export const Stocks = () => {
return (
<>
<div className="stock-container">Welcome to Stock Tracker</div>
</>
);
};
Add the css class stock-container inside src/App.css file. The code inside the App.css file should look like this.
.App {
text-align: center;
}
.stock-container {
padding-left: 3em;
padding-right: 3em;
margin-top: 3em;
}
Go to the browser and open https://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.
import { stockData } from "./data";
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.
import React from "react";
import "./App.css";
import { stockData } from "./data";
export const Stocks = () => {
return (
<>
<div className="stock-container">
{stockData.map((data, key) => {
return (
<div key={key}>
{data.company +
" , " +
data.ticker +
" ," +
data.stockPrice +
", " +
data.timeElapsed}
</div>
);
})}
</div>
</>
);
};
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 https://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:
- Add a <HomePageHeader> component to display a header.
- Add a <Stock> component that accepta data in props and renders a table on the web page.
- 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.
const HomePageHeader = () => {
return (
<header className="header">
<h2>Your Stock Tracker</h2>
</header>
);
};
The <HomePageHeader> component also uses a CSS class header, so we need to add it inside src/App.css.
.header {
background-color: #f4e04d;
min-height: 10vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: #10375c;
}
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.
```js
const Stock = ({ company, ticker, stockPrice, timeElapsed }) => {
if (!company) return <div />;
return (
<table>
<tbody>
<tr>
<td>
<h5>{company}</h5>
</td>
<td>
<h5>{ticker}</h5>
</td>
<td>
<h4>{stockPrice}</h4>
</td>
<td>
<p>{timeElapsed}</p>
</td>
</tr>
</tbody>
</table>
);
};
```
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.
```css
table {
display: flex;
justify-content: center;
border: 1px solid gray;
}
td {
border: 1px solid gray;
width: 30em;
}
```
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.
```js
export const Stocks = () => {
return (
<>
<HomePageHeader />
<div className="stock-container">
{stockData.map((data, key) => {
return (
<div key={key}>
<Stock
key={key}
company={data.company}
ticker={data.ticker}
stockPrice={data.stockPrice}
timeElapsed={data.timeElapsed}
/>
</div>
);
})}
</div>
</>
);
};
```
Make sure your src/Stocks.js looks exactly like this before you view the webpage in your browser.
```js
import React from "react";
import "./App.css";
import { stockData } from "./data";
export const Stocks = () => {
return (
<>
<HomePageHeader />
<div className="stock-container">
{stockData.map((data, key) => {
return (
<div key={key}>
<Stock
key={key}
company={data.company}
ticker={data.ticker}
stockPrice={data.stockPrice}
timeElapsed={data.timeElapsed}
/>
</div>
);
})}
</div>
</>
);
};
const HomePageHeader = () => {
return (
<header className="header">
<h2>Your Stock Tracker</h2>
</header>
);
};
const Stock = ({ company, ticker, stockPrice, timeElapsed }) => {
if (!company) return <div />;
return (
<table>
<tbody>
<tr>
<td>
<h5>{company}</h5>
</td>
<td>
<h5>{ticker}</h5>
</td>
<td>
<h4>{stockPrice}</h4>
</td>
<td>
<p>{timeElapsed}</p>
</td>
</tr>
</tbody>
</table>
);
};
```
Go to the browser and open https://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.
Learn More
Explore these React courses from Pluralsight to continue learning: