Read Locally JSON File Use Fetch Method In React js?

Post image

Let’s start it.


  1. Folder Structure
  2. JSON File Structure
  3. Read JSON File.

Folder Structure:

React Folder Structure.

Our JSON File place Inside Public Folder In React.js Project. ReactJS Public Folder Access By URL.

JSON File Structure:

JSON File Structure

JSON File Structure Most Important For Us, Because when JSON Data Warp Inside Array. In case You Use Map() Method And Get Data Easily Inside Your Project.

        "username": "officialrajdeepsingh",
        "firstName": "Rajdeep",
        "lastName": "Singh",
        "gender": "Male",
        "aboutAuthor": "Read Book, Music Lover and Web Developer"

You Write Directly Inside JSON File You Use Object.entries() Method Firstly, after use map() method For Read JSON File. Rest Of Code Same In My Demo Project.JSON data Access Not Easily In Object.entries() Method. I’m Recommend You To Wrap Your JSON Data Firstly Inside the Array.

    "username": "officialrajdeepsingh",
    "firstName": "Rajdeep",
    "lastName": "Singh",
    "gender": "Male",
    "aboutAuthor": "Read Book, Music Lover and Web Developer"

Read JSON File:

// react
import React,{useState} from "react";
// Own Css 
import "./styles.css";

export default function App() {
// react Hook For State Handler
  const [data , setData]=useState(null)

// Fetch Function   
    return res.json()
  // store Data in State Data Variable
      console.log(err, ' error')

  return (
    <div className="App">
        // use data State Variable For Get Data Use JavaScript Map Mathod
                  return (<div className="card"> 
                  <h4> {data.username}</h4>
                  <h2> {data.firstName}  {data.lastName}</h2>
                  <h3> {data.gender}</h3>
                  <h3> {data.aboutAuthor}</h3>
  • Inside Fetch Method, We Pass Public Folder File Name Only.
  • In My Case My File Inside Public Folder. So we use look like “./data.json”.But Do Not Use Absolute Path Look Like “./public/data.json”.
  • Then use json() method Get data From The Response.
  • Do Not use Import File, Inside Fetch Method URL.
  • React.js Server Convert Public Folder File Access With URL to HTTP Response.
  • Make Sure Your JSON File Access With URL (Checkout My Example URL).

Local Development Access Your File Inside React.js App


Example My React Demo Project


Read More:

Contact me

You May Also Like

comments powered by Disqus