Search code examples
reactjsenumsinternationalizationi18nextreact-i18next

react-i18Next: Using an enum for translation key values


We are using i18Next in our React project and I wonder if there is way to use an enum for keys of the translation file to avoid typos while using it like this:

export enum AppLocaleKey {
  test = 'test'
}

...

import translationEN from './locales/en/translation';
const resources = {
  en: { translation: translationEN },
  ...
};

i18n
  .use(initReactI18next)
  .init({
    resources,
    ...
  })

...

const translation = {
  [AppLocaleKey.test]: 'Test...',
};

export default translation;

...

import { AppLocaleKey } from './locales/localeKeys';
import { useTranslation } from 'react-i18next';

const App = (props: Props) => {
  const { t, i18n } = useTranslation();
  return (
    <>
      <p>{t(AppLocaleKey.test)}</p>
    <>
  )
}

But this didn't work. Do you know any similar method?


Solution

  • If you are using TS you can with ts4.1 declare all the keys of the json as a valid inputs.

    Check out the official example,

    And working example out of it.