How to implement language switcher using next-intl

2k Views Asked by At
"use client";
import { useLocale } from "next-intl";
import { locales, localeNames } from "../../i18nconfig";
import { useRouter } from "next/router";
import Link from 'next/link';
import { Fragment } from "react";

export default function LocaleSwitcher(){
    const locale = useLocale();
    const router = useRouter();

    const switchLocale = (newLocale: string) => {
        router.push({
            pathname: router.pathname,
            query: router.query
        }, router.asPath, {locale: newLocale});
    };

    return(
        <div className="flex space-x-1">
        {locales.map((loc) => (
            <Fragment key={loc}>
            <Link href="/" locale={loc} passHref legacyBehavior>
                <a
                className={`text-blue-500 hover:underline ${
                    locale === loc ? 'font-semibold' : ''
                }`}
                onClick={() => switchLocale(loc)}
                >
                {localeNames[loc]}
                </a>
            </Link>
            {loc !== locales[locales.length - 1] && (
                <span className="font-semibold">|</span>
            )}
            </Fragment>
        ))}
    </div>
    )
}

I'm trying to change the language of the page using Next.js Intl. When I use next/router, I get the above error. I have tried switching to next/navigation, but I can't find how to implement the functionality of changing my locale for EN and ES

2

There are 2 best solutions below

0
On

You seem to have 2 separate issues here.

  1. Replace next/router with next/navigation. Here's the docs

The useRouter hook should be imported from next/navigation and not next/router when using the App Router

import { useRouter } from "next/navigation";
  1. Changing translations. You seem to be mapping all your translations and using both Link logic and push logic instead of using only one at a time. And I don't see the reason why you need to add language in params rather than in router for example /[locale]/contact. I suggest taking a look at nextjs docs and on locale switcher implementation
0
On

Here is an official app router locale switcher example: https://next-intl-example-app-router.vercel.app/en

On that page you will also find a link to source code. I used it myself recently and it worked for me.