2

Is there a way to translate something using the next-i18next library without changing the locale with router.push?

I have 3 locales: ['en', 'de', 'fr'], the default being de. When I am trying to do something like:

import {useTranslation} from 'next-i18next'

const Component = () => {
  const { t } = useTranslation("common");
  console.log(t('word', { lng: 'fr' }));
}

while my current locale is de, it returns the de translated version, not the fr.

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337

1 Answers1

0

If refer to this doc https://react.i18next.com/latest/usetranslation-hook there is no possibility to translate something without change whole system language, you can change system language using 2 ways:

one you described router.push

another is:

const { t, i18n } = useTranslation();

i18n.changeLanguage('de');
console.log( t('word') );
i18n.changeLanguage('en-US');

But this solution is very ugly because you will switch whole system lang just for very small log.

If you will describe real case, probably a can help you find real solution. Real case means why you need log translated word on DE and so on.

Yuriy Gyerts
  • 1,464
  • 18
  • 30
  • I tried the solution with `changeLanguage` and it still does not work. Why I need to this is in order to have translated `URLs`. And in order to do this I have to take and translate the whole URL before sending it as `asPath` to `router.push`. The problem that I have is that from what I reckon, `next-i18next` gives me access only to the current locale language and the default one, ignoring the others from the `locales` array. – Topliceanu Razvan May 26 '21 at 16:19
  • Could you please provide with an example of raw url (with no translation) and how would you like to translate it – Yuriy Gyerts May 26 '21 at 16:27
  • en: `/london/results` -> fr: `/londres/resultats` – Topliceanu Razvan May 26 '21 at 16:30
  • Any way such arrays with translated links should be kept on backend, not on frontend. like `{ 'some.article', slug: { en: 'SomeArticle', fr: 'LaFranceArticle' } }`. On FE you should just use already translated slug for your future URL – Yuriy Gyerts May 26 '21 at 16:31
  • I know and you are right, but the problem is that we have around 7k links – Topliceanu Razvan May 26 '21 at 16:32
  • Now definitely I will say that you have to keep all this translation on BE because your frontend chank size will be very very very very very large. Need to find elegant solution, FE is not elegant solution at all. – Yuriy Gyerts May 26 '21 at 16:36
  • t(“mykey”, { lng: “de” }) – adrai May 28 '21 at 22:43