Search code examples
next.jsnext-intl

How to implement language switcher using next-intl


"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


Solution

  • 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.