Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading local JSON file in React for dynamic content

Im trying to figure out the best way of accessing the local JSON file and storing it in my current state. I hope i am in the right track :)

Project.js

import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom";

// framer motion
import { motion } from "framer-motion";

const Project = (props) => {
const { projectID } = useParams();
const [project, setProject] = useState({});

  useEffect(() => {
    fetch('src/data/projects.json', {
      headers: {
        "Content-Type": "application/json",
        "Accept": "application/json",
      },
    })
      .then((res) => res.json())
      .then((data) => console.log(data));
  }, []);

  return (
    <motion.div exit={{ opacity: 0, transition: { duration: 1 } }}></motion.div>
  );
};

export default Project;

JSON FILE

[
{
  "title": "Example",
  "id": "1",
  "src": "example.png"
},
{
  "title": "Example 2",
  "id": "2",
  "src": "example-2.png"
}
]

enter image description here

like image 873
jmvdc Avatar asked Nov 03 '25 03:11

jmvdc


1 Answers

This clearly looks like your relative path is not correct.

UPDATE: From the comments and cross checking it is clear that we must move our json file into a public folder for it to work.

So you need to first do that and directly use this path:

fetch('data/projects.json',

HERE IS THE DEMO: https://codesandbox.io/s/json-fanda-stydg?file=/src/App.js

like image 58
Imran Rafiq Rather Avatar answered Nov 05 '25 18:11

Imran Rafiq Rather



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!