How to Display Data from Json File in react step by step
To display data from a JSON file in a React application, you can follow these steps:
Step 1: Set Up Your React Project
If you haven’t created a React project yet, you can do so using Create React App. Open your terminal and run the following commands:
npx create-react-app my-json-app cd my-json-app
Replace “my-json-app” with the desired name for your project.
Step 2: Create a JSON File
Create a JSON file with the data you want to display. For example, you can create a file named ‘data.json’ in your project’s ‘public’ folder:
// public/data.json { "items": [ { "id": 1, "name": "Item 1", "description": "Description for Item 1" }, { "id": 2, "name": "Item 2", "description": "Description for Item 2" }, { "id": 3, "name": "Item 3", "description": "Description for Item 3" } ] }
Step 3: Create a Component to Display Data
Create a new React component that will display the data. For example, you can create a component named ‘DataDisplay.js’:
// src/components/DataDisplay.js import React, { useState, useEffect } from 'react'; const DataDisplay = () => { const [data, setData] = useState([]); useEffect(() => { // Fetch data from the JSON file fetch('/data.json') .then((response) => response.json()) .then((jsonData) => setData(jsonData.items)) .catch((error) => console.error('Error fetching data:', error)); }, []); // Empty dependency array ensures the effect runs only once return (); }; export default DataDisplay;Data Display
{data.map((item) => (
- {item.name}: {item.description}
))}
This component uses the ‘useState’ and ‘useEffect’ hooks to fetch data from the JSON file when the component mounts. It then maps over the data array to display each item in an unordered list.
Step 4: Include the Component in App.js
Include the ‘DataDisplay’ component in your ‘src/App.js’ file:
// src/App.js import React from 'react'; import DataDisplay from './components/DataDisplay'; function App() { return (); } export default App;
Step 5: Run Your React App
Save your files, and in the terminal, run:
npm start
This command will start the development server, and you can view your React app by navigating to http://localhost:3000 in your browser. You should see the data from the JSON file displayed on the page.
Adjust the file paths and component names based on your project structure.