Skip to content

Instantly share code, notes, and snippets.

@rmsy
Last active July 1, 2020 00:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmsy/94506e20ef57b57fcd7f432ef66e0689 to your computer and use it in GitHub Desktop.
Save rmsy/94506e20ef57b57fcd7f432ef66e0689 to your computer and use it in GitHub Desktop.
This is a slight re-write of the component created [here](https://lingui.js.org/guides/dynamic-loading-catalogs.html) to be a functional component and support a priority-ordered list of multiple locales.
import React, { useCallback, useEffect, useState } from "react";
import { Catalog } from "@lingui/core";
import { I18nProvider } from "@lingui/react";
export type I18nLoaderProps = {
locales: string[];
};
/**
* This component attempts to load the first available compiled message catalog for the array of passed in locales. If
* none are available, the children are not rendered.
*
* This is a based on the component created [here](https://lingui.js.org/guides/dynamic-loading-catalogs.html).
*/
export const I18nLoader: React.FC<I18nLoaderProps> = (props) => {
const [locale, setLocale] = useState(null as string | null);
const [catalog, setCatalog] = useState(null as Catalog | null);
const loadCatalog = useCallback(async () => {
for (let i = 0; i < props.locales.length; i++) {
// Try to load the catalog for the current locale
try {
const currLocale = props.locales[i];
const loadedCatalog = await import(
/* webpackMode: "lazy", webpackChunkName: "i18n-[index]" */
`@lingui/loader!../../locales/${currLocale}/messages.po`
);
// If we found a supported locale/catalog, update the state and bail
if (loadedCatalog) {
setCatalog(loadedCatalog);
setLocale(currLocale);
return;
}
} catch (_) {}
}
}, [props.locales]);
useEffect(() => {
loadCatalog().then();
}, [loadCatalog]);
// Skip rendering when no supported locales are available.
if (!locale || !catalog) return null;
return (
<I18nProvider language={locale} catalogs={{ [locale]: catalog }}>
{props.children}
</I18nProvider>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment