Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NextJS i18 trigger page reload on locale change

How exactly do I trigger a page reload from the code after user selects the language?

I'm using Next JS 10.0 and the new i18 features so my two urls are

  • localhost/en/dashboard
  • localhost/sp/dashboard

On my react button click I tried

router.push(`/${lang}/Dashboard`)

This works however is there a way where I don't have to manually re-code the current page location?

like image 238
user391986 Avatar asked Oct 15 '25 08:10

user391986


2 Answers

I had the same issue and I just reload the page after the change language, but first you need to wait till the locale is completely changes then reload the page:

const handleChangeLanguage = (lang) => {
    router.push(router.pathname, router.asPath, {locale: lang});

    router.events.on('routeChangeComplete', () => {
        router.reload()
    });
}
like image 167
Jason Avatar answered Oct 16 '25 21:10

Jason


You must not use the lang or locale as part of your url string. Try the following instead.

    router.push('/dashboard', '/dashboard', { locale: 'YOUR_NEW_LOCALE' })

In case you're wondering why there are two '/dashboard', its because the first one goes as a to the second is an as. You can read about it more here

like image 28
Muljayan Avatar answered Oct 16 '25 21:10

Muljayan



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!