react-i18next

The preset for react-i18next and next-i18next. It reads useTranslation, Trans and Translation, plus everything of i18next.

The react-i18next preset supports react-i18next and next-i18next.

Detection

The preset applies when the project depends on react-i18next or next-i18next. x18n still tests the presets after it, such as i18next and general.

x18n.config.ts
import { reactI18next } from '@x18n/cli/presets'
import { defineConfig } from '@x18n/core'

export default defineConfig({
  presets: [reactI18next()],
})

What it adds

The preset includes everything of the i18next preset: the : namespace separator, the default namespace translation, the derived keys {key}_*, the placeholders and the calls of i18next. If the i18next preset also applies, x18n adds these plugins one time.

Supported syntax

import { Trans, Translation, useTranslation } from 'react-i18next'

function Page() {
  const { t } = useTranslation('common', { keyPrefix: 'buttons' })
  return (
    <>
      <button>{t('save')}</button>
      <Trans i18nKey="welcome" ns="pages" />
      <Translation ns="pages">{t => <h1>{t('title')}</h1>}</Translation>
    </>
  )
}
  • useTranslation(ns, { keyPrefix }) returns a t with a namespace and a key prefix. t('save') above is common:buttons.save.
  • <Trans i18nKey="..." ns="..."> is a usage of its i18nKey.
  • <Translation ns="..."> passes a t with the namespace to its child function.
  • const { i18n } = useTranslation() makes i18n.t a translate call.
  • withTranslation('ns')(Component) sets the namespace for the whole file, because the component gets its t through props and is often above the call.

Placeholders

The same as for i18next: {{name}} and $t(key).

Extraction templates

KindsTemplateImports
jsx-text<Trans i18nKey="{key}" />import { Trans } from 'react-i18next'
jsx-attribute{attr}={i18next.t('{key}'{args})}import i18next from 'i18next'
js-string, js-templatei18next.t('{key}'{args})import i18next from 'i18next'