You can achieve this by using Next.js's internationalization routing. You can define a lang parameter in your file path and use it to determine the language of your page. Here's how you can do it:
-
Create a lang parameter in your file path. For example, your file path could be app/[lang]/page.js.
-
In your app/[lang]/page.js file, you can fetch the dictionary for the current language using the getDictionary function. Here's an example:
import { getDictionary } from './dictionaries'
export default async function Page({ params: { lang } }) {
const dict = await getDictionary(lang)
return <button>{dict.products.cart}</button>
}
In this example, lang is the currently selected language, which is fetched from the URL. The getDictionary function then loads the translations for the requested locale.
- You can define your dictionaries in
dictionaries/en.json and dictionaries/nl.json files. Here's an example of what your dictionaries/en.json file could look like:
{
"products": {
"cart": "Add to Cart"
}
}
- You can then create a
getDictionary function to load the translations for the requested locale:
import 'server-only'
const dictionaries = {
en: () => import('./dictionaries/en.json').then((module) => module.default),
nl: () => import('./dictionaries/nl.json').then((module) => module.default),
}
export const getDictionary = async (locale) => dictionaries**locale** ()
In this example, the getDictionary function imports the appropriate dictionary based on the locale parameter, which is the currently selected language.
This way, you can check which page a user is on and pass the appropriate props based on the language of the page.