Toggle preferred locale in request header using language switcher - i18n.
Unanswered
Firelord Ozai posted this in #help-forum
Hello everyone. I have my Next.js app setup with internationalization using the quick example from the Next.js docs: https://nextjs.org/docs/app/building-your-application/routing/internationalization. This works so far, and the preferred locale is available. How can I setup a language switcher to update the preferred locale in the request header to the one the user selects?
Here's my current language switcher component
I've tried creating a
Will appreciate any form of help or pointers. Thanks.
Here's my current language switcher component
"use client";
import { i18n } from "@/i18n-config";
import { ChangeEvent, useState } from "react";
import { usePathname, useRouter } from "next/navigation";
const language = [
{
name: "English",
locale: "en",
},
{
name: "Français",
locale: "fr",
},
];
export default function Switcher() {
const router = useRouter();
const pathname = usePathname();
const [languageType, setLanguageType] = useState<string>(i18n.defaultLocale);
function handleOnChange(event: ChangeEvent<HTMLSelectElement>) {
const customLocale = event.target.value;
setLanguageType(customLocale);
router.push(`/${customLocale}${pathname}`);
}
return (
<div>
<select
value={languageType}
onChange={handleOnChange}
>
{language.map((lang) => (
<option key={lang.locale} value={lang.locale}>
{lang.name}
</option>
))}
</select>
</div>
);
}I've tried creating a
NEXT_LOCALE cookie to store the value of the currently selected locale and try to persist the preferred language using this cookie but it didn't work.Will appreciate any form of help or pointers. Thanks.
1 Reply
Bumping this question.