Dynamic translation routing with Next.js

My goal is to create dynamic translation routes for specific pages in next js using i18next. While the following code works well, it currently routes to all pages and generates errors during next build.

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

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

I'm aiming to implement these dynamic translation routes only for the home and about page. One potential workaround would be to separate the translation route links from the navbar and place them wherever needed. However, I prefer to integrate this translation functionality within the navbar component for reusability on every page. Is there a way to achieve this in a reusable component?

Answer №1

Check out this link for more information on how to include a locale option:

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

Alternatively, you can use

Router.push(path, path, {locale: 'fr'})
. Don't forget that you can also add an onclick event handler if you prefer using a button.

Answer №2

Clicking on any of the translation buttons will change the default locale to the selected one. To prevent certain pages from being translated, I decided to add a default locale="en" to the links where translation was not necessary.

For example, I didn't want the events page to be translated, but because the default locale changes when the translation button is clicked on another page, the events page was still being routed to /fr/events if the default locale was changed to fr. To resolve this issue, I made the following adjustment..

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

In addition, @JeanJacquesGourdin's solution offers a simpler way to direct the page to the chosen language without requiring a more complicated route in my own solution.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide for animating individual mapped elements in react-native?

After mapping an object array to create tag elements with details, I added an animation for the tags to zoom in on render. However, I wanted to take it further and animate each tag individually, sequentially one after the other. This appears to be a common ...

Issue with Materialize Sidenav: Not functional on iOS devices including iPhones, functions correctly on all other devices

My Materialize Sidenav is functioning on all devices except for iPad and iPhone. If you want to check out the code, here is the link to the repository: repo. Take a look at index.html (line 44 down) and js/onloadSetup.js. I attempted adding this in onload ...

Include a query parameter each time a page is added to bookmarks

Is there a way to automatically add a query parameter to a page URL when bookmarked using Chrome? For example, if I bookmark https://www.example.com, can it be saved as https://www.example.com/?bookmarked? I'm thinking I might need to use JavaScript ...

Using fast refresh in Next.js is leading to a fetch error when integrated with Express.js

When trying to fetch data from my API, I encountered an error due to fast refresh in Next.js. It seems that req.params only work once because of a bug with Next.js's fast refresh feature. Do you know of any solutions or alternative ways to retrieve th ...

How can we redirect to another page after checking a box?

In the scenario where a checkbox is checked, how can the page be automatically redirected to @habit, simulating the behavior of clicking a submit button? habits/show <% if @habit.current_level_strike %> <div class="btn" id="red"> <l ...

What is the best way to swap out particular phrases within HTML documents or specific elements?

Trying to update specific strings within an HTML document or element. How do I go about parsing and replacing them? To clarify: - Identify all instances of #### in element .class - Swap them out with $$$$$ Currently utilizing jQuery for this task. Appre ...

Is there a way to determine the quantity of child objects and transmit the calculated index to each individual child object?

My data is structured as shown below: team1 : { author92 : "John" , author43 : "Smith" }, team2 : { author33 : "Dolly", author23 : "Mark" }, I want to display Authors grouped together with an ad ...

Issue with locale being undefined in NextJS Internationalization (i18n) Routing

Currently, I am delving into the realm of Next.js Internationalization (i18n) Routing for my personal website. Despite my efforts, the values for locale, locales, and default locale are displaying as undefined. (I am working with the most recent version of ...

String values should determine whether a checkbox is checked or not

When retrieving data from LocalStorage, my code looks like this: angular.module('madMeApp').controller('campaignInDetails', function($scope) { var campaignToShow = JSON.parse(localStorage.getItem("CampaignDetails")); $scope.selecte ...

What strategies can I use to optimize the code for the function provided?

This function allows for the dynamic display of select tags for location selection based on employee designation. The current code functions correctly, but I believe it can be optimized further. // Function to activate different location options based on e ...

Encountered an error in production mode with Angular 7: Uncaught ReferenceError - "environment" variable

During development, my application runs smoothly, and ng build --prod --source-map successfully compiles the application. However, when attempting to access it through the browser, an error occurs: app.module.ts:47 Uncaught ReferenceError: env is not defi ...

Inability to update Vue.js component data even after a successful GET request

I am encountering an issue with a component that initially contains a default object, and then fetches a populated object via a GET request upon creation. Despite successfully updating this.profile within the method, the changes do not seem to propagate ...

Selenium and JavaScript integration for opening new browser tabs

Hello there, I am looking to open new tests ('it' method) in new tabs and currently trying this approach: driver = new Builder().forBrowser('chrome').build(); beforeEach(() => { // driver.manage().window().open('url') ...

Create a feature that allows users to view photos similar to the way it

I want to incorporate a Twitter feed on my website that displays images posted. Instead of having the images redirecting users to Twitter when clicked, I would like them to reveal themselves underneath when a link labeled "View Photo" is clicked, and then ...

Problem with HTML relative paths when linking script sources

Having trouble with a website I constructed using Angular. The problem lies in the references to javascript files in index.html. The issue is that the paths in the HTML are relative to the file, but the browser is searching for the files in the root direct ...

Poorly formatted mui table representation

I have utilized the Table component from @mui/material and referenced the documentation at https://mui.com/material-ui/react-table/. To reproduce the issue, I have created a static table with fixed values. Here is the code snippet: <TableCo ...

Using Selenium to scroll down to an element until its 'style' changes

I'm in the process of scraping a review page similar to this one. While this specific page has only a few reviews, there are others with a larger volume that require extensive scrolling. Upon observation, I noticed that when the page is not complete ...

Encountering a challenge with Nuxt where I am unable to navigate back when utilizing the require method

After successfully viewing the image, I encountered an error when trying to navigate back using <NuxtLink :to="{ path: 'About', hash: '#secondNav' }" class="close">, which resulted in a message stating Cannot f ...

Is there a way for me to retrieve the text response of a fetch request from client-side JavaScript to fastify server?

In my fastify node.js application, I am encountering an issue where I can see the text results of a promise right before it is returned to the browser's JavaScript code. However, once the promise is returned to the browser JS, all I get is an empty st ...

Prevent the execution of a Javascript function if it is already in progress

I've developed a function that retrieves records from a third party, and this function runs every 10 seconds. However, as I debug through Firefox, I notice a long queue of ajax requests. I'm contemplating including a statement that can signal to ...