4
"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

1
  • Here is an official app router locale switcher example: 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. Commented Dec 16, 2023 at 7:42

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.