One approach could be to create a a script tag in the index.html file and add your JSON/Data to the window object and access it inside the React Components.
index.html
.... Other html data
<script>
// freeze if you want object to be immutable
window.INITIAL_DATA = Object.freeze({
name: 'Hello World',
settings: {
dateFormat: 'yyyy-mm-dd',
},
});
// use templating engine to store JSON String in object
const INITIAL_DATA_JSON = `{
"name": "Hello World",
"settings": {
"dateFormat": "yyyy-mm-dd"
}
}`;
// Parse and store JSON Object
window.APP_INITIAL_DATA= JSON.parse(INITIAL_DATA_JSON);
</script>
// Notice Script Tag comes before root div, so that when react renders the object is present
<div id="root"></div>
.... Other html data
And then in your react component you could access it like the following
export default function App() {
// Access it
const initialData = window.APP_INITIAL_DATA;
console.log(window.APP_INITIAL_DATA);
return (
<div>
<h1>{initialData.name}</h1>
<p>{initialData.settings.dateFormat}</p>
</div>
);
}
If you are using TypeScript in your react project you might need to extend the Window Interface, otherwise typescript will throw an error.
Extending Window Interface
windowand retrieve it from there in any part of your Reactjs application.DOMParserto parse the HTML will be longer. Reconsider your design.fetch()the JSON asynchronously.