How to access/fetch the local JSON file to React.

Vahid Akhtar
3 min readNov 2, 2020

--

Project Structure

In this guide, you’ll learn how to save and read the local JSON file in the react project.

Three ways of accessing the local JSON file.

  • From JSON file inside src
  • How to read JSON file using react API call(fetch, Axios).
  • JSON data in the js file inside src

Inside src (No Need Axios or Fetch for api call).

Save your JSON file inside src anywhere for example —

folder structure

then import and read inside any component like below.

State-Try to assign and handle through the state because the state is dynamic, it enables a component to keep track of changing information in between renders and for it to be dynamic and interactive.

For the class-based component —

state = {
usersData: users
}

Output —

How to read JSON file using reactjs API call(fetch, axios).

Sometimes we need to test something locally so many times that’s why needed fake data instead of calling the API.

If your JSON data is in a public folder that is outside of src.

and you want to make an API call. public -> data.json

Note- For class-based components make API calls insidecomponentDidMount lifecycle method.

Output —

Note: We need URL parameters while using Axios and Fetch.

JSON data in the js file

if JSON data is saved in a javaScript file like below —

import and read like —

Output —

Complete code- https://github.com/akhtarvahid/local-json-react.git

Thanks for reading and stay tuned!

Links and Resources

--

--