Table of contents
No headings in the article.
Introduction
JSON stands for JavaScript Object Notation.JSON is a lightweight format for storing and transporting data.JSON is often used when data is sent from a server to a web page.JSON is "self-describing" and easy to understand. JavaScript objects are an integral part of the React app, so they need to get accessed from JSON files/data to be uses in components.
This blog will demonstrate how to get a JavaScript object from a JSON file or access it using a fetch() HTTP request.
Rendering Values from a JSON File
Create one sample JSON file as given below, and save it as data.json
{
"employees":{
"employee1": {"firstName":"John", "lastName":"Doe"},
"employee2": {"firstName":"Anna", "lastName":"Smith"},
"employee3": {"firstName":"Peter", "lastName":"Jones"}
}
}
Now, if you want to render any of the key-value pairs from the JSON, the .map() function would be useful to iterate the objects; the example is below.
import React, { Component } from "react";
// Import local JSON file
import Data from "./data";
export class Sample extends Component {
render() {
return (
<>
<div>
<h3>Using local JSON file</h3>
{Object.keys(Data.employees).map((item, i) => (
<li key={i}>
<span>Key name : {item}</span>
</li>
))}
</div>
</>
);
}
}
export default Sample;
In the above example, to use the local JSON file needs to be consumed using the import statement.
import Data from "./data";
After that, you can access all the JSON data using Data in your component by using Object.keys() along with the .map() function.
{Object.keys(Data.employees).map((item, i) => ())}
Using a local JSON file in the React app is a common approach when you want to render some static data, maintain server config, etc.
Rendering JSON Objects from an API Call
You have seen the example where a local JSON file is used, but at the same time you may need to access JSON data from the server.
Implement the API call as demonstrated below.
componentDidMount() {
fetch("https://jsonplaceholder.typicode.com/users")
.then(res => res.json())
.then(
result => {
this.setState({
data: result
});
},
error => {
console.log(error);
}
);
}
After implementing the API call, you can access the JSON data for the rendering as below.
render() {
return (
<>
<div>
<h3>Using API call</h3>
{this.state.data &&
this.state.data.length > 0 &&
this.state.data.map((item, i) => (
<li key={i}>
<span>Email : {item.email}</span>
</li>
))}
</div>
</>
);
}
Along with the state this.state.data, the additional function used is .map(), which iterates the array items from the state and renders them into the DOM.