I have a React app (with static content, not using Node.js) and i need to load a configuration file (JSON).
The file loading needs to be in runtime, because the configuration needs to have different data, related with the server where the application is hosted.
Due this last requirement, i can't load the file using, for instance, webpack externals, because the application doesn't update the configurations when the the JSON file is updated.
What is the best way to do that?
I've done that using the Fetch API (http request to load the file), but maybe there's a better way to do that.
You have at least 2 options here depending on your use case:
data-attribute
on my root with the server url
that will hold my config data (as in my case I don't know the domain
of the server at compile time). i.e: <div id="root" data-url="yourDomain.com/app"></div>
.
Grab this value and pass it
as prop in to the App. index.js
for example:
const root = document.getElementById('root');
const url = root.getAttribute('data-url');
const configPromise = fetch(url);
configPromise.then((res) => res.json())
.then(config => render(<App config={config} />, root) );
I like the first option more even though it forces you to do an ajax request.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With