react-tiny-translation
v1.0.1
Published
simple localisation manager for react
Downloads
1
Maintainers
Readme
react-tiny-translation
Use tiny-translation in the React applications
Install
npm i tiny-translation react-tiny-translation
// or
yarn add tiny-translation react-tiny-translation
Usage
You can use different files for translates. Below I use follow example files
lang_ru.json
{
"screens": {
"Home": {
"title": "Заголовок",
"description": "Описание ${desc} ${name}",
"plural": {
"zero": "${COUNT} бананов",
"one": "${COUNT} банан",
"two": "${COUNT} банана",
"few": "${COUNT} банана",
"many": "${COUNT} бананов",
"other": "${COUNT} бананов"
}
}
}
"extrapoint": {
"anything": "Что-нибудь"
}
}
lang_en.json
{
"screens": {
"Home": {
"title": "Title",
"description": "Description ${desc} ${name}",
"plural": {
"zero": "${COUNT} bananas",
"one": "${COUNT} banane",
"two": "${COUNT} bananas",
"few": "${COUNT} bananas",
"many": "${COUNT} bananas",
"other": "${COUNT} bananas"
}
}
}
"extrapoint": {
"anything": "Anything"
}
}
TranslationProvider
import { Translation } from 'tiny-translation';
import { TranslationProvider } from 'react-tiny-translation';
import ru from './lang_ru.json';
import en from './lang_en.json';
enum Locale {
ru = 'ru',
en = 'en',
}
const translation = new Translation<Locale>({
translations,
locale: Locale.ru
});
export const App: React.FC = () => (
/**
* translation: Translation<Locale>;
* initLocale: Locale;
* pluralRecord?: Record<Locale, PluralFn>;
*/
<TranslationProvider translation={translation}>
...
</TranslationProvider>
);
useTranslate
export const SomeComponent: React.FC = () => {
/**
* t: Translate<T>;
* locale: string;
* changeLocale: (locale: string) => Promise<void>;
*/
const { t, locale, changeLocale } = useTranslate`extrapoint`
return (
<div>
{t`anything`}
</div>
)
};
useTranslationContext
export const SomeComponent: React.FC = () => {
/**
* loading: boolean; // it changes during dynamic import
* translation: Translation;
*/
const { loading, translation } = useTranslationContext()
return (
<div>
...
</div>
)
};
withTranslate
import { TranslateProps, withTranslate } from 'react-tiny-translation';
/**
* t: Translate<T>;
* locale: string;
* changeLocale: (locale: string) => Promise<void>;
*/
export const SomeComponent: React.FC<TranslateProps> = ({ t, locale, changeLocale }) => {
return (
<div>
{t`anything`}
</div>
)
};
const TranslatedSomeComponent = withTranslate('extrapoint')(SomeComponent);
// or
const translated = withTranslate`extrapoint`;
const TranslatedSomeComponent2 = translated(SomeComponent);
About translate
, changeLocale
you can read in the tiny-translation doc