@xtreamsrl/react-i18n
v0.1.6
Published
This package exposes a set of hooks to manage app internationalisation and localisation.
Downloads
441
Readme
@xtreamsrl/react-i18n
This package exposes a set of hooks to manage app internationalisation and localisation.
Installation
npm install @xtreamsrl/react-i18n
Usage
Wrap the main app with the I18nProvider
and set up translations with configureTranslation
:
// app.tsx
import { configureTranslation, I18nProvider } from '@xtreamsrl/react-i18n';
const translations = {
it: {
welcome: 'Benvenuto'
},
};
configureTranslation(translations);
export function App() {
const [localeFromSlice, setLocaleFromSlice] = useState('it');
return (
<I18nProvider locale={localeFromSlice} changeLocale={setLocaleFromSlice}>
<MainApp />
</I18nProvider>
);
}
Use the following available hooks as needed:
useTranslate
: used for simple translationsuseDateTimeFormat
: used for date-time formattinguseTranslateWithFormatting
: used for translating and formatting at the same time by leveraging existing app components.
// Component.tsx
import { useTranslation } from '@xtreamsrl/react-i18n';
export function Component() {
const t = useTranslation();
return (
<h1>
<span>{t('welcome')}</span> 👋
</h1>
);
}
The useDateTimeFormat
hook can be used to format dates and times.
Everything works in a very similar way to the string translation, but with the addition of the format
parameter.
Generally, all the possible formats are listed in an enum:
export enum DateTimeFormat {
ONLY_YEAR_MONTH_STANDARD = 'date.formats.default',
FULL_DATE = 'date.formats.full',
FULL_DATE_TIME = 'time.formats.fullDateTime',
}
This means that the keys in the translation object must be the same as the enum values. In other terms the translation object will contain both the literal translations and the date-time formats.
const translations = {
it: {
welcome: 'Benvenuto',
date: {
formats: {
default: '%Y-%m',
full: '%d/%m/%Y',
},
},
time: {
formats: {
fullDateTime: '%d/%m/%Y %H:%M',
},
},
},
};
The useDateTimeFormat
hook can be used as follows:
// Component.tsx
import { useDateTimeFormat } from '@xtreamsrl/react-i18n';
export function Component() {
const dtf = useDateTimeFormat();
const date = new Date();
return (
<span>
{dtf(date, DateTimeFormat.FULL_DATE_TIME)}
</span>
);
}