2

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.

  • _"this is routing to all pages and generating errors while `next build`"_ - Can you clarify what you mean by this? What errors are you getting during build? – juliomalves Jun 27 '22 at 21:33
  • next build was building pages for non translated pages, example /fr/events which doesn't exists. It was happening for all the other pages as well. – Mohammed Rehan Jun 29 '22 at 09:43

2 Answers2

1

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

JeanJacquesGourdin
  • 1,496
  • 5
  • 25
0

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.