rsnext/examples/with-i18n-rosetta/lib/i18n.js
Steven 4466ba436b
chore(examples): use default prettier for examples/templates (#60530)
## Description
This PR ensures that the default prettier config is used for examples
and templates.

This config is compatible with `prettier@3` as well (upgrading prettier
is bigger change that can be a future PR).

## Changes
- Updated `.prettierrc.json` in root with `"trailingComma": "es5"` (will
be needed upgrading to prettier@3)
- Added `examples/.prettierrc.json` with default config (this will
change every example)
- Added `packages/create-next-app/templates/.prettierrc.json` with
default config (this will change every template)

## Related

- Fixes #54402
- Closes #54409
2024-01-11 16:01:44 -07:00

52 lines
1.3 KiB
JavaScript

import { createContext, useState, useRef, useEffect } from "react";
import rosetta from "rosetta";
// import rosetta from 'rosetta/debug';
const i18n = rosetta();
export const defaultLanguage = "en";
export const languages = ["de", "en"];
export const contentLanguageMap = { de: "de-DE", en: "en-US" };
export const I18nContext = createContext();
// default language
i18n.locale(defaultLanguage);
export default function I18n({ children, locale, lngDict }) {
const activeLocaleRef = useRef(locale || defaultLanguage);
const [, setTick] = useState(0);
const firstRender = useRef(true);
const i18nWrapper = {
activeLocale: activeLocaleRef.current,
t: (...args) => i18n.t(...args),
locale: (l, dict) => {
i18n.locale(l);
activeLocaleRef.current = l;
if (dict) {
i18n.set(l, dict);
}
// force rerender to update view
setTick((tick) => tick + 1);
},
};
// for initial SSR render
if (locale && firstRender.current === true) {
firstRender.current = false;
i18nWrapper.locale(locale, lngDict);
}
// when locale is updated
useEffect(() => {
if (locale) {
i18nWrapper.locale(locale, lngDict);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [lngDict, locale]);
return (
<I18nContext.Provider value={i18nWrapper}>{children}</I18nContext.Provider>
);
}