Josh
Josh

Reputation: 464

create-react-app Static Site - Reading JSON file

I'll preface by saying that I'm new to React, so hopefully there's a simple answer that I just missed somewhere.

In short, I want to build a page that I can run without any kind of webserver. I have everything configured so I can just open index.html and it runs fine.

The problem, however, is that I want a data.json file that can be edited after the project is built (essentially a config file) so I can't just stick it inside the /src folder because it all gets bundled.

data.json

{
  "timeout": 10,
  "threshold": 50
}

import React from 'react';

const App = () => {      
  const path = process.env.PUBLIC_URL + '/data/data.json';
  fetch(path)
  .then((res) => res.text())
  .then((json) => {
    const data = JSON.parse(json);
  })

  return (
   ...
  );
}

This may work fine when running in VSCode, but throws CORS errors when running the index.html page by itself. I also know that I can't just reference the a file directly in /public because it's outside the /src folder:

import data from '../Public/data/data.json';

How can I have a configurable file in /Build that I can read in from React without running into CORS issues.

Hopefully this question makes sense

Thanks

Upvotes: 0

Views: 341

Answers (2)

Josh
Josh

Reputation: 464

I was able to workaround this problem by injecting the configs into the window object in the index.html file. It's pretty hacky but it allows me to edit the index.html file and configs after the projects been built. I'd love to hear some better solutions.

index.html

<script>
  window.__data = {
    "timeout": 10,
    "threshold": 50
  }
</script>

App.tsx

const App = () => {      
  const data = (window as any).__data;

  return (
   ...
  );
}

Upvotes: 0

ludwiguer
ludwiguer

Reputation: 2245

There is no need to prepend the PUBLIC_URL env variable.

This should work

fetch('/data/data.json')

Upvotes: 1

Related Questions