-1

My backend server generates the initial index.html page that loads the react app, ie.:

<html>
  <.... src="..../app.js" />
<body>
...DOM element that loads reactjs app
</body>
</html>

Now within this index.html page, could I have inlined a JSON object that my reactjs app could reference directly? (as oppose to making an axios http GET request to fetch this data).

The goal is to have this data loaded by reactjs directly instead of making another http request to fetch this data.

5
  • If the JSON is large then UX wise, not a good idea. Nonetheless you can load it into the global window and retrieve it from there in any part of your Reactjs application. Commented Jun 23, 2024 at 9:39
  • @ChukwujiobiCanon what is large? why is it not a good idea UX wise? Commented Jun 24, 2024 at 17:12
  • Inline JSON within HTML? If it is large then UX wise, it is not a good idea. Commented Jun 24, 2024 at 18:24
  • @ChukwujiobiCanon UX is user experience - how will it effect UX? Commented Jun 24, 2024 at 19:19
  • 1
    I will lead to slow page load. The time it will take the DOMParser to parse the HTML will be longer. Reconsider your design. fetch() the JSON asynchronously. Commented Jun 25, 2024 at 7:53

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

is this a common approach?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.