How to access the local JSON file to React.

How to access the local JSON file to React.

React is a popular JavaScript library for building user interfaces. It can be used to create interactive and dynamic web applications. One of the great things about React is that it is easy to integrate with other libraries and frameworks. This makes it possible to use React to build applications that access and fetch data from a variety of sources, including local JSON files. In this blog post, we will show you how to access/fetch a local JSON file in React. We will use the JSON-loader package to import the JSON file into our React project. We will then use the map() method to iterate over the data in the JSON file and render it to the DOM.

Step 1: First Create and Save your JSON file inside src anywhere for example

[
    {
        "id": 4,
        "name": "Lee Graham",
        "username": "Bret",
        "email": "Sincere@april.biz"
    },
    {
        "id": 1,
        "name": "Leanne Graham",
        "username": "Bret",
        "email": "Sincere@april.biz"
    },
    {
        "id": 2,
        "name": "Ervin Howell",
        "username": "Antonette",
        "email": "Shanna@melissa.tv"
    },
    {
        "id": 5,
        "name": "Leffe Graham",
        "username": "Bret",
        "email": "Sincere@april.biz"
    }
]

Step 2: Import the JSON file

we can import the JSON file into our React project. To do this, we need to add the following import statement to our app.js file:

import data from './data.json';

The data variable will now contain the data from the data.json file.

Step 3: Iterate over the data in the JSON file

Now that we have imported the JSON file, we can iterate over the data in the file and render it to the DOM. To do this, we can use the map() method. The map() method takes two arguments: an iterable object and a callback function. The iterable object in this case is the data object. The callback function in this case takes one argument: an item from the data object.

The following code shows how to iterate over the data in the JSON file and render it to the DOM:

import React, { Component } from 'react';
import data from './data/data.json';

class App extends Component {
  render() {
    return (
      <div>
        {data.map((item, index) => (
          <div key={index}>
            <h1>{item.name}</h1>
            <p>{item.email}</p>
          </div>
        ))}
      </div>
    );
  }
}

export default App;

The app component renders a div element that contains a list of div elements. Each div element in the list contains an h1 element with the name property from the item in the data object and a p element with the email property from the item in the data object.

I hope this explanation is helpful. Let me know if you have any other questions.

Did you find this article valuable?

Support Amit Gajare by becoming a sponsor. Any amount is appreciated!