Next js dynamic routing for translation

Viewed 101

I'm trying to set dynamic routes for translation for specific pages in next js using i18next. The following code works well, but this is routing to all pages and generating errors while next build.

const router = useRouter();
const path = router.route; 

<Link href={`/fr${path}`}>
   French
</Link>
<Link href={`/es${path}`}>
   Spanish
</Link>

I want to have this dynamic translation routes only for 2 pages that is home and about page. The other workaround would be to seperate the translation routes link from the navbar and have it where ever needed. But, I want to achieve this translation through the navbar component so that I can reuse the component on every page. Is there a way to approach this in a reusable component.

2 Answers

As you can see here, you can provide a locale option, something like :

<Link href={`/${path}`} locale='fr'>
   French
</Link>

or Router.push(path, path, {locale: 'fr'}) If you want to use a button with on click

When any of the translation buttons are clicked, the default locale is changes to the selected locale. I didn't want some pages to translate, So the easy fix was to include a default locale="en" to the links where translation was not needed.

e.g: I didn't want to translate the events page, but since the default locale changes when translation button is clicked on any other page. The events page was also being routed to /fr/events if the default locale is changed to fr. To fix it I did the following..

<Link href="/events" locale='en'>
   Events
</Link>

Also the answer provided by @JeanJacquesGourdin is a simple way to route the page to selected language instead of a more complex route in my solution.

Related