Search code examples
next.jsi18nextreact-i18nextnext-i18next

Why isn't my t() texts refreshing in localhost/en but refreshing in localhost/fr on i18n.changeLanguage()?


Hi

I just made a website with a darkmode and multilanguage support to test around but I ran into an issue.

the code

I got rid of all things that aren't an issue

portfolio/src/pages/index.tsx

import { useTranslation } from 'react-i18next'
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';

export default () => {
  const { t,i18n } = useTranslation('common')
  return <div onClick={()=>i18n.changeLanguage(i18n.language=='fr'?'en':'fr')}>
    <div>{i18n.language}</div>
    <span>{t('debug')}</span>
  </div>
}

export async function getStaticProps({ locale }:any) {
  return {
    props: {
      ...(await serverSideTranslations(locale, ['common'])),
      // Will be passed to the page component as props
    },
  };
}

portfolio/src/public/locales/en/common.js

{"debug":"english"}

portfolio/src/public/locales/fr/common.js

{"debug":"français"}

portfolio/next-i18next.config.js

const path = require("path");

module.exports = {
  debug: false,
  i18n: {
    defaultLocale: 'en',
    locales: ['en', 'fr'],
  },
  localePath: path.resolve('./src/public/locales'),
};

portfolio/src/pages/_app.tsx

import '../styles/globals.css'
import type { AppProps } from 'next/app'
import {appWithTranslation} from 'next-i18next'

export default appWithTranslation(({ Component, pageProps }: AppProps) => {
  return <Component {...pageProps} />
})

The issue

When I do npm run dev and go to http://localhost:3000/fr, the page defaults to french and works good I can swap between languages without problems but when i go to http://localhost:3000/en the t('debug') doesn't translate when the i18n.language changes as intended.


Solution

  • Found what I wanted

    So basicaly I need to use a next Link that will change the local and the link

    Code application

    index.js

    //...
    export default () => {
      const { t,i18n } = useTranslation('common')
      return (
        <div>
    
          <Link 
            href={i18n.language=='fr'?'/en':'/fr'} 
            locale={i18n.language=='fr'?'en':'fr'}
          >{i18n.language}</Link>
    
          <div>{t('debug')}</div>
    
        </div>
      )
    }
    //...
    

    result

    Now the text changes as intended both in the /fr and /en because it switches between the 2 however the result is far from smooth. It reloads the page and i'd like to avoid that because I use some animations on it.

    Found what i wanted part 2

    Browsing through the next-i18next documentation I found what I wanted.

    solution

    I needed to load the props using getStaticProps and in the serverSideTranslation function i needed to pass as argument the array off ALL the language necessary to load the page ['en','fr'] because i switched between the 2