Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hook useTranslation() don't read imported namespaces - i18next

I'm importing jsons with translations in my React project so I can organize my code. But the useTranslation() hook doesn't seem to read these imported namespaces.

An example of how I'm doing that:

i18n.js:

import i18next from 'i18next';
import {
  file1, 
  file2
} from 'translations';

i18next.init({
  interpolation: {
    escapeValue: false
  },
  lng: 'en',
  resources: {
    en: {
      file1: file1,
      file2: file 2
}
export default i18next;

Using useTanslator():

import React from 'react';
import { useTranslation } from 'react-i18next';

export function MyComponent() {
  const { t } = useTranslation();

  return
   <p>{t('file1:text')}</p>
   <p>{t('file2:file2.text')}</p>
}

It shows:

text

file2.text

Edit: I had add the namespaces like useTranslation("file1") but still doesn't work.

like image 386
IaraCordeiro Avatar asked Oct 17 '25 16:10

IaraCordeiro


2 Answers

You need to double check initialization parameters in i18n.js file. You should specify namespace separator (nsSeparator).The rest should follow official documentation.

.init({
...........
 resources,
 ns: ['file1', 'file2'],
 defaultNS: 'file1',
 nsSeparator: ':'
..............
})
like image 149
Elchin Guseynov Avatar answered Oct 20 '25 06:10

Elchin Guseynov


You're missing the namespaces when you call the hook. It should be:

useTranslation(["file1", "file2"])
like image 26
sunero4 Avatar answered Oct 20 '25 07:10

sunero4



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!