How to fetch data from local JSON file in React JS

Cynthia

React.js is a popular JavaScript library for building user interfaces, and often, you'll need to retrieve data from various sources. One common scenario is fetching data from a local JSON file. In this blog post, we'll walk through the steps to fetch data from a local JSON file in a React.js application.

Prerequisites

Before we begin, ensure you have the following prerequisites:

  1. Node.js and npm: Make sure you have Node.js and npm (Node Package Manager) installed on your computer. You can download them from nodejs.org.

  2. React Project: You should have an existing React project or create a new one. You can create a new React app using Create React App or any other setup of your choice.

Step 1: Create a React App (If Needed)

If you don't have a React project, you can create one using Create React App. Open your terminal and run the following command:

npx create-react-app json-fetch-app

Replace json-fetch-app with your preferred project name.

Step 2: Organize Your JSON Data

For this example, let's assume you have a local JSON file named data.json with the following structure:

{
  "users": [
    {
      "id": 1,
      "name": "John Doe",
      "email": "john@example.com"
    },
    {
      "id": 2,
      "name": "Jane Smith",
      "email": "jane@example.com"
    }
    // Add more user data here
  ]
}

Place this data.json file in your project's src directory.

Step 3: Create a Component to Fetch Data

Now, let's create a React component that fetches and displays data from the data.json file. In your src directory, create a new file named UserData.js:

// src/UserData.js
import React, { useState, useEffect } from "react";

const UserData = () => {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    // Fetch data from the local JSON file
    fetch("/data.json")
      .then((response) => response.json())
      .then((data) => setUsers(data.users))
      .catch((error) => console.error("Error fetching data:", error));
  }, []);

  return (
    <div>
      <h1>User Data</h1>
      <ul>
        {users.map((user) => (
          <li key={user.id}>
            <strong>{user.name}</strong> - {user.email}
          </li>
        ))}
      </ul>
    </div>
  );
};

export default UserData;

In this component:

  • We initialize a state variable users using the useState hook to store the data from the JSON file.
  • We use the useEffect hook to fetch data when the component mounts. The fetch function is used to make a GET request to the data.json file.
  • If the request is successful, we convert the response to JSON and update the users state with the user data.
  • We display the user data in an unordered list (<ul>) using the map function.

Step 4: Use the Component in Your App

Now, let's use the UserData component in your main App.js file:

// src/App.js
import React from "react";
import "./App.css";
import UserData from "./UserData";

function App() {
  return (
    <div className="App">
      <UserData />
    </div>
  );
}

export default App;

Step 5: Running the Application

Start your React application by running:

npm start

Open your web browser and navigate to http://localhost:3000. You should see the user data fetched from the local JSON file displayed on the page.

Conclusion

In this blog post, we've demonstrated how to fetch data from a local JSON file in a React.js application. We used the fetch function to make a GET request to the JSON file, converted the response to JSON, and displayed the data in a component. This technique can be useful when you need to retrieve data stored locally within your application. You can adapt this approach to fetch and display data from various sources and APIs in your React projects.