Next.js Discord

Discord Forum

How to toggle language with NextJS internationalization

Answered
American posted this in #help-forum
Open in Discord
AmericanOP
Hi everyone! Migrating my project from pure react to nextjs, got struggled with toggling language on click. Previously, with just react, I used i18n.changeLanguage and t functions from i18next.

In case of NextJS I implemented middleware and dictionaries from docs (I made internationalization using sub-paths)
https://nextjs.org/docs/app/building-your-application/routing/internationalization

With these steps followed, I now have { params } prop in my server components, and I can use dict["key"] for translations. The question is, how can I toggle languages with one button. Surely, I can manually check, something like:
import { usePathname } from "next/navigation";

const Component = () => {
  const pathname = usePathname();
  const toggleLanguage = () => {
    // considering we have SR and RU languages on the website
    router.push(pathname.includes("sr") ? "/ru" + pathname.slice(2) : "/sr" + pathname.slice(2))  
  }

  return <button onClick={toggleLanguage}>Toggle</button>
}


But this seems like a bad way doing things. Is there a proper way of toggling language? I hope to find some "graceful" solution with NextJS internationalization features or i18n ones.

Worth mentioning, in the docs link above, you can switch to pages version and seems like there is a way to do the thing, but only for pages router:
https://nextjs.org/docs/pages/building-your-application/routing/internationalization#transition-between-locales
Answered by American
Thanks for sharing, I figured it out with your realization. Now with custom util function and Link usage it looks fine

// util functions file: 
export const getNewURL = (path: string) => {
  if (path.includes("/sr")) {
    return path.replace("/sr", "/ru");
  } else {
    return path.replace("/ru", "/sr");
  }
};


// Navigation.tsx
const Navigation = () => {
  const pathname = usePathname();
  ...
  return (
    ...
    <Link href={getNewURL(pathname)}>
      Change language
    </Link>
  )
}
View full answer

3 Replies

Hey @American , I built something similar recently. should probably help - https://github.com/dayoawobeku/onex-rswe-assessment-2024-starter/tree/master
@Dayo Hey <@329572469432254465> , I built something similar recently. should probably help - https://github.com/dayoawobeku/onex-rswe-assessment-2024-starter/tree/master
AmericanOP
Thanks for sharing, I figured it out with your realization. Now with custom util function and Link usage it looks fine

// util functions file: 
export const getNewURL = (path: string) => {
  if (path.includes("/sr")) {
    return path.replace("/sr", "/ru");
  } else {
    return path.replace("/ru", "/sr");
  }
};


// Navigation.tsx
const Navigation = () => {
  const pathname = usePathname();
  ...
  return (
    ...
    <Link href={getNewURL(pathname)}>
      Change language
    </Link>
  )
}
Answer