How to display JSON key-value pairs in ReactJS
When working with data from APIs or
Loading and parsing JSON data
Let's say we have a JSON object with information about a user, such as their name, age, city, country, and email address.
{"Name": "John Doe","Age": 21,"City": "Lahore","Country": "Pakistan","Email": "Johndoe@gmail.com"}
We want to use a React component to show this data. For this, we have to follow these steps.
Create a React component
Use that component in App.js
Render the application
Creating a component
Start by creating a new file called JsonDisplay.js in your React project's components folder. In this file, define a functional component called JsonDisplay:
import React from 'react';const JsonDisplay = ({ data }) => {return (<div>{Object.entries(data).map(([key, value]) => (<div key={key}><strong>{key}:</strong> {value}</div>))}</div>);};export default JsonDisplay;
Explanation
Line 3: This line defines a functional component called
JsonDisplay. It uses ES6 arrow function syntax. The component receives a prop calleddata, which will be the JSON object we want to display.Line 7:
Object.entries(data)converts thedataJSON object into an array of key-value pairs.Lines 8–11:
Array.map()is used to iterate over each key-value pair in the array and return a new array of JSX elements.Line 10: The
keyprop is set to thekeyvalue of the current key-value pair. This is required for React to update and manage the rendered elements efficiently.Line 12: The
valueof the key-value pair is displayed as the text next to the label.
Integrating the component in App.js
In the parent component, import the JsonDisplay component and use it to display the JSON data.
import React from 'react';import JsonDisplay from './JsonDisplay';import jsonData from './Json_data.json';const App = () => {return (<div><h1>JSON Display</h1><JsonDisplay data={jsonData} /></div>);};export default App;
Explanation
Line 8:
<JsonDisplay>component is rendered with thedataprop set to the importedjsonDataobject. This passes the JSON data to theJsonDisplaycomponent for rendering.
Rendering the application
Finally, render the App component in your main index.js file or any other root file of your React application.
import React from 'react';import ReactDOM from 'react-dom';import App from './App';ReactDOM.render(<App />, document.getElementById('root'));
Explanation
Line 5: This line renders the React application by mounting the
Appcomponent onto the DOM.ReactDOM.render()is a method used to render React components to the DOM. It takes two arguments: the component to render and the target DOM element where the component will be rendered.
Output
Free Resources