Reading a .json
file in a React application is quite straightforward. Here are the steps to do it:
Create a JSON file: First, create a JSON file with some data. For example, let’s name it
data.json
and place it in thesrc
folder of your React project.{ "users": [ { "id": 1, "name": "John Doe" }, { "id": 2, "name": "Jane Smith" } ] }
Import the JSON file: In your React component, import the JSON file.
import React from 'react'; import data from './data.json'; const App = () => { return ( <div> <h1>User List</h1> <ul> {data.users.map(user => ( <li key={user.id}>{user.name}</li> ))} </ul> </div> ); }; export default App;
Run your React app: Start your React application using
npm start
oryarn start
, and you should see the list of users displayed on the screen.
This method works well for small JSON files and local data. If you need to fetch data from an external API, you can use libraries like Axios or the Fetch API12.
Would you like more details on fetching data from an external source or anything else?
Comments
Post a Comment