React Intl: Asynchronously loading a singular locale's data in a Universal Application

Hey there, I'm currently working on a universal app that supports multiple languages using React. I'm facing challenges with handling locale data efficiently. The app will be available in 16 different languages with a large amount of translated messages. Loading all the messages in one big JSON file or including them in the webpack bundle is not feasible due to the size of the data. I need a way to dynamically load the user's language messages only when needed. I've managed to achieve this on the client side, but now I also need it to work on the server side. My setup includes Express for server side rendering and webpack for bundling. Can anyone provide insights on the best approach to tackle this issue?

Answer №1

I have recently been exploring a similar concept, although my project does not involve SSR. I have discovered that combining dynamic import syntax with React's Suspense component has helped me achieve the desired outcome in my scenario. Results may vary depending on whether you require SSR, but here is a general overview of what has worked for me:

// Implement this structure in your JSX within App.js:
<React.Suspense fallback={<SomeLoadingComponent />}>
  <AsyncIntlProvider>
    {/* Place app child components here */}
  </AsyncIntlProvider>
</React.Suspense>

// Additional support can be implemented as follows,
// and can be stored in another file
// Simply import AsyncIntlProvider in App.js

const messagesCache = {};

const AsyncIntlProvider = ({ children }) => {
  // Adjust the logic to retrieve your app's locale information
  // If based on something like useState, it should trigger a re-render and load new message bundle when the locale changes
  const locale = getLocale();

  const messages = getMessages(locale);
  return (
    <IntlProvider locale={locale} messages={messages}>
      {children}
    </IntlProvider>
  );
};

function getMessages(locale) {
  if (messagesCache[locale]) {
    return messagesCache[locale];
  }
  // Suspense relies on ErrorBoundary
  // Throwing a promise will result in rendering <SomeLoadingComponent /> until the promise resolves
  throw loadMessages(locale);
}

async function loadMessages(locale) {
  // Utilizing dynamic import syntax prompts webpack to split this module into its own chunk
  const messages = await import('./path/to/${locale}.json`);
  messagesCache[locale] = messages;
  return messages;
}

Make sure that Webpack separates each locale JSON file into its individual chunk. Failure to do so might indicate that the dynamic import syntax is being transpiled to a different module system (require, etc.) before reaching webpack. For instance, when using Typescript, tsconfig requires "module": "esnext" to preserve the import() syntax. Babel might also attempt module transpilation.

The resulting chunk for a single locale could resemble the following structure:

(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[0],{

/***/ "./path/to/en-US.json":
/*!*************************************!*\
  !*** ./path/to/en-US.json ***!
  \*************************************/
/*! exports provided: message.id, default */
/***/ (function(module) {

eval("module.exports = JSON.parse(\"{\\\"message.id\\\":\\\"Localized message text\\\"}\");//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiLi9zcmMvbG9jYWxpemF0aW9uL2VuLVVTLmpzb24uanMiLCJzb3VyY2VzIjpbXSwibWFwcGluZ3MiOiIiLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///./path/to/en-US.json\n");

/***/ })

}]);

I trust this information proves helpful as you embark on internationalizing your project! 😁

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Performing React axios requests to an Express API on a Heroku server deployment

I have been working on a React todo app that I created using create-react-app. In order to retrieve all the appointment objects, I built a simple express server that queries mongoDB. It functions perfectly when running locally on my machine - with the fron ...

Having trouble fetching data (node.js) from my client (react.js)

I'm experiencing difficulty retrieving the data I send from the client to the server. Below is my react code: axios.post('http://localhost:5000/post-entry', { data: formData }) .then(res => { console.log(res); }) This is my server cod ...

Images stored locally are not appearing in React JS applications

I'm currently exploring React JS and Material UI to develop a dynamic web application. I'm attempting to link a local image using 'url(${process.env.PUBLIC_URL})' but unfortunately, the image is not showing up for some unknown reason. ...

When attempting to import my JSX file into page.js, I continue to encounter the error "module not found." How can I troubleshoot and resolve this issue in Visual Studio Code

I recently created a new file called mysec.jsx in the components folder of src. I then used the export function to properly export it. However, when I tried to import this file in page.js using the import function, I encountered an error message that said: ...

What is the best way to retrieve the value from a React Img element?

I am having an issue with receiving 'undefined' from the console.log in 'handleClickVideo'. How can I properly extract the value when clicking on a video? I attempted using a div as well, but since div does not have a value property, it ...

Using CSS to style in React is throwing an error: "TypeError: Cannot read property 'image' of undefined"

Hi there! I'm fairly new to web development and React, and I could really use some guidance with my current project. I've been working on pulling data from a local file and trying to display it upon click. Everything goes smoothly until I start ...

Creating a React child component with conditional rendering is a useful technique to dynamically display

Typically, we create child components in React like this: const component =(<button>Bla Bla</button>) But what if you want to create it using a conditional statement? You might try something like this: const component =(()=>{ if(true){ re ...

Utilize the information retrieved from generateStaticParams (Next 14 days)

It's interesting to see how generateStaticParams functions. Typically, we retrieve one id to create each segment. While the API call used for this purpose contains the necessary data to populate each page generated at build time, it seems impossible ...

What is the reason for Google Chrome extension popup HTML automatically adding background.js and content.js files?

While using webpack 5 to bundle my Google Chrome extension, I encountered an issue with the output popup HTML. It seems to include references to background.js and content.js even though I did not specify these references anywhere in the configuration file. ...

Error: Attempting to access an undefined property ('call') on Next.js is causing a TypeError

Exploring the realms of Next.js and Typescript for a new project! My goal is to utilize next.js with typescript and tailwind CSS by simply entering this command: npx create-next-app -e with-tailwindcss my-project Smooth sailing until I hit a snag trying t ...

Numbering Tables Effectively in ReactJS

Currently working on coding a table in ReactJS and MUI, my goal is to number the No. column from 1 to the length of the array. This snippet shows my code: <TableBody> {quizes.map((quiz, index) => ( <TableRow key={quiz._id}> ...

Is there a specific reason why a <ContextProvider> higher order component is not updating its default value?

export const FocusContext = React.createContext({ isUsingMouse: true, setIsUsingMouse: () => { console.error("FocusContext.Provider value not initialized"); }, }); export const FocusContextProvider = ({ children }) => { ...

Having trouble with the firebase module import in ReactJS?

Encountering an Error . /firebase.js:2:0 Module not found: Package path . is not exported from package C:\Users\krish\Desktop\FACEBOOK _CLONE\facebook_clone\node_modules\firebase (see exports field in C:\Users\ ...

The function purported by WEBPACK_MODULE_13___default(...) does not exist

Scenario : I've been working on a small library (let's call it myLibrary) using TypeScript and Webpack. Everything seemed to be running smoothly until I imported the library into a React application, which resulted in a crash. On the Library Sid ...

Cracking the code of the @ symbol within this particular context

https://github.com/react-dnd/react-dnd/blob/master/examples/04%20Sortable/Simple/Card.js I'm trying to comprehend the significance of the @ symbol in this example. This is meant to be a straightforward drag and drop demonstration, but the implementa ...

How to Display All User Avatars Using SupaBase Public URL?

Utilizing Next.js framework with SupaBase I am attempting to retrieve all user avatars stored in a column within the "Profiles" table. https://i.stack.imgur.com/wGgrO.png Currently, I am only receiving the image name "placeholder.png". How can I extract ...

The useParams() function will return an empty value upon the component's initial render

I'm utilizing React along with the following libraries: "babel-eslint": "10.0.3", "react": "^17.0.2", "react-dom": "^17.0.2", "react-redux": "^7.2.4", "react-router-dom": "^6.3.0", "react-scripts": "3.2.0", "redux": "^4.1.1 ...

What is the best way to insert a permanent script tag into the body of a Gatsby site? Can conditional rendering be used to control

As an illustration: - const nation = "USA" import chat from './utils/script'; // script is imported from a file if(nation === "USA") // utilized conditionally in the component { chat } else { console.log("Not USA") } inform me witho ...

How can I use the form's restart() method in React-Final-Form to clear a MUI TextField input and also capture the event at the same time?

When I use form.restart() in my reset button, it resets all fields states and values based on my understanding of the Final-Form. The reset method triggers and clears all fields in the form, and I can capture the event in the autocomplete. However, I am fa ...

Having trouble transmitting data with axios between React frontend and Node.js backend

My current challenge involves using axios to communicate with the back-end. The code structure seems to be causing an issue because when I attempt to access req.body in the back-end, it returns undefined. Here is a snippet of my front-end code: const respo ...