Deep Kakkar
Deep Kakkar

Reputation: 6307

How to switch back to the default locale in Next.js?

In the Next.js app, I am using the next-i18next module for multi-language which is working fine. There are two languages one English and the other Arabic. Default is English.

For toggle, I am using the following code in NavBar.

import { useRouter} from "next/router"
import { useTranslation } from 'next-i18next'
import { useState } from 'react'

const NavBar = ({...props}) => {
    const router = useRouter()
    const { t } = useTranslation('navbar');
    const [language, setLanguage] = useState(router.locale)

const onChangeLanguage = (lang) => (e)=> {
        e.preventDefault()
        if(lang === 'ar') {
            router.push('ar')
        } else {
            
            router.push('/')
        }
    }

return (
  <>
    .....
    .....
    <div className="form-check form-check-inline">
      <input type="checkbox" className="form-check-input" id="en" onClick={onChangeLanguage('en')} value="en" defaultChecked = {language === 'en'} />
      <label className="form-check-label" htmlFor="inlineCheckbox1">English</label>
    </div>
    <div className="form-check form-check-inline">
      <input type="checkbox" className="form-check-input" id="ar" onClick={onChangeLanguage('ar')} value="ar" defaultChecked = {language === 'ar'} />
      <label className="form-check-label" htmlFor="inlineCheckbox2">Arabic</label>
    </div>
  </>
 )
}

export default NavBar;

So on the homepage i.e. http://localhost:3000 when I check the Arabic language then it appends /ar after the URL and works good but it creates issues in the internal pages.

I have pages structure like

pages
   index.js
   settings 
      locations
        index.js
        add.js
        edit
          [...id].js
      products
        index.js
        add.js
        edit
           [...id].js

If I try to change the locale from en to ar on the internal page e.g. http://localhost:3000/settings/products then it redirects on the http://localhost:3000/settings/ar URL where it does not find any route so 404 appears.

In case if I have set ar locale from the homepage [http://localhost:3000/ar] then If I change the locale from ar to en on any internal page e.g. http:localhost:3000/ar/settings/localtion/edit/<UUID> then it does not set language as en.

Upvotes: 1

Views: 7055

Answers (1)

juliomalves
juliomalves

Reputation: 50278

To keep the current route but change the locale, you can use router.asPath as the url then pass the locale in the options object (third argument) of router.push.

const onChangeLanguage = (lang) => (e) => {
    e.preventDefault()
    router.push(router.asPath, undefined, { locale: lang })
}

Upvotes: 3

Related Questions