Fetching data is a fundamental part of building dynamic web applications. Often, you might need to load data from a local JSON file during development or when building a small-scale application. In this blog post, we’ll guide you through the steps to fetch data from a local JSON file in a React JS application.
Prerequisites
Before we start, ensure you have the following:
- A basic understanding of React JS.
- Node.js and npm installed on your machine.
- A React project set up. If you don’t have one, you can create it using Create React App:
npx create-react-app fetch-local-json
cd fetch-local-json
npm start
Steps to Fetch Data from a Local JSON File
Step 1: Create a Local JSON File
First, create a local JSON file in the public
directory of your React project. This directory is accessible by the web server, making it a good place to store static files.
Create a file named data.json
in the public
directory and add some sample data:
// public/data.json
[
{
"id": 1,
"name": "John Doe",
"email": "john.doe@example.com"
},
{
"id": 2,
"name": "Jane Smith",
"email": "jane.smith@example.com"
}
]
Step 2: Fetch Data in a React Component
Next, we’ll fetch this data in a React component. Create a component named UserList.js
in the src
directory and use the useEffect
and useState
hooks to fetch and display the data.
// src/UserList.js
import React, { useEffect, useState } from 'react';
function UserList() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch('/data.json')
.then((response) => response.json())
.then((data) => setUsers(data))
.catch((error) => console.error('Error fetching data:', error));
}, []);
return (
<div>
<h2>User List</h2>
<ul>
{users.map((user) => (
<li key={user.id}>
{user.name} - {user.email}
</li>
))}
</ul>
</div>
);
}
export default UserList;
Step 3: Use the Component in Your App
Now, import and use the UserList
component in your main App.js
file to display the fetched data.
// src/App.js
import React from 'react';
import UserList from './UserList';
function App() {
return (
<div className="App">
<header className="App-header">
<h1>Fetching Data from Local JSON</h1>
<UserList />
</header>
</div>
);
}
export default App;
Step 4: Run the Application
Run your application using:
npm start
You should see the list of users fetched from the local data.json
file displayed on the screen.
Conclusion
Fetching data from a local JSON file in a React application is straightforward. By placing the JSON file in the public
directory and using the fetch
API, you can easily load and display data. This approach is useful for development and small projects where a local JSON file can act as a simple data source.
Feel free to expand on this example by adding error handling, loading states, and more complex data structures as required by your application. Happy coding!