Can't find this exact question answered. I want to have a data.JSON file in my /public folder which contains a static file which once site is built I can quickly modify without having to rebuild the site. However I'm struggling on how to get this into react. I've tried following instructions from the README, but it's a bit unclear.
If I try:
class Home extends Component {
render() {
const data = require(`${process.env.PUBLIC_URL}/data.json`);
I get the message on compile:
./src/Home.js
Module not found: You attempted to import /data.json which falls outside of the project src/ directory. Relative imports outside of src/ are not supported. You can either move it inside src/, or add a symlink to it from project's node_modules/.
What's the proper way to include it? I also tried a hacky way by trying to write it to window.DATA in public/index.html but because I believe it has to call Asynchronous (otherwise chrome gives me an error) sometimes the data will be there, sometimes not, and React doesn't seem to like it. Code I tried:
var request = new XMLHttpRequest();
request.open("GET", "%PUBLIC_URL%/data.json", true);
request.send(null);
request.onreadystatechange = function() {
if ( request.readyState === 4 && request.status === 200 ) {
window.DATA = JSON.parse(request.responseText);
}
}
Any help would be appreciated!
data.jsonfile is outside thesrcdirectory you'll have to use an absolute path, or put yourdata.jsonfile within the/src/directory of your project if you want to use a relative path.