0.1.6 • Published 9 months ago

@xtreamsrl/react-i18n v0.1.6

Weekly downloads
-
License
-
Repository
github
Last release
9 months ago

@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 translations
  • useDateTimeFormat: used for date-time formatting
  • useTranslateWithFormatting: 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>
  );
}

Who we are

0.1.6

9 months ago

0.1.5

2 years ago

0.1.4

2 years ago

0.1.3

2 years ago

0.1.2

2 years ago