When working with data from APIs or
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
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;
Line 3: This line defines a functional component called JsonDisplay
. It uses ES6 arrow function syntax. The component receives a prop called data
, which will be the JSON object we want to display.
Line 7: Object.entries(data)
converts the data
JSON 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 key
prop is set to the key
value of the current key-value pair. This is required for React to update and manage the rendered elements efficiently.
Line 12: The value
of the key-value pair is displayed as the text next to the label.
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;
Line 8: <JsonDisplay>
component is rendered with the data
prop set to the imported jsonData
object. This passes the JSON data to the JsonDisplay
component for rendering.
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'));
Line 5: This line renders the React application by mounting the App
component 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.
Free Resources