@pl-pluto/locale
v0.2.15
Published
```bash yarn add @pl-pluto/locale ```
Readme
@pl-pluto/locale
Install
yarn add @pl-pluto/localeUsage
Initialize
import { enDictionary } from './en';
import { huDictionary } from './hu';
import { initializeLocalization } from '../initialize';
import { pickIsoLanguageCountry } from '../language/isoLanguages';
import { createBaseLocale } from '../locale/baseLocale';
export const {
baseLocale,
createLocales,
createDictionary,
supportedLanguages,
} = createBaseLocale(pickIsoLanguageCountry(['en-US', 'hu-HU']), {
language: 'en-US',
dictionary: {
foo: 'bar',
languageName: {
'hu-HU': 'Hungarian',
'en-US': 'English',
},
},
});
export type SupportedLanguages = (typeof supportedLanguages)[number];
export const {
LocaleProvider,
useLocale,
defaultLanguage,
locales,
provideLocale,
getLocale,
} = initializeLocalization({
baseLocale,
translations: createLocales({
'hu-HU': createDictionary({
foo: 'bar',
languageName: {
'hu-HU': 'Magyar',
'en-US': 'Angol',
},
}),
}),
supportedLanguages,
defaultLanguage: baseLocale.language,
});Usage in Next App router
Export this middleware and wrap your pages inside a [lang] folder
export const { config, middleware } = provideLocale();Use the locale in any component
const ServerHero = () => {
const { t } = getSSRLocale();
return <h1>{t.foo}</h1>;
};You can change the locale by navigating to it
const LanguageChanger = () => {
const {onLanguageChange, supportedLanguages, language, t} = getSSRLocale();
return (
<select
value={language}
onChange={(event) => {
onLanguageChange(event.target.value
as
SupportedLanguages
)
;
}}
>
{supportedLanguages.map((lang) => (
<option key={lang} value={lang} selected={lang === language}>
{t.languageName[lang]}
</option>
))}
</select>
);
};Usage in React App
Use the provider in the top level of your app
const App = ({ children }) => {
return <LocaleProvider>{children}</LocaleProvider>;
};Use the locale with the provided hook
const Hero = () => {
const { t } = useLocale();
return <h1>{t.foo}</h1>;
};Use the hook to change the language
const LanguageChanger = () => {
const { language, onLanguageChange, supportedLanguages, t } = useLocale();
return (
<div>
<select
value={language}
onChange={(event) => {
onLanguageChange(event.target.value as SupportedLanguages);
}}
>
{supportedLanguages.map((lang) => (
<option key={lang} value={lang} selected={lang === language}>
{t.languageName[lang]}
</option>
))}
</select>
</div>
);
};
