next-app-dir-i18next-example-ts
next-app-dir-i18next-example-ts copied to clipboard
TypeError: i18n.changeLanguage is not a function when i tried add a language change button
🐛 Bug Report
I don't want to disturb others, but I have spent two nights and read many articles, but I can't get any results. I tried to add a LanguageSwitcher component and introduced it in page.tsx, but when I clicked the button, i got the error: TypeError: i18n.changeLanguage is not a function
How can i add a very very simple button to switch language? Thanks
'use client';
import { useTranslation } from 'react-i18next';
export default function LanguageSwitcher() {
const { i18n } = useTranslation();
const changeLanguage = (lng: string) => {
i18n.changeLanguage(lng);
};
return (
<div>
<button onClick={() => changeLanguage('de')}>de</button>
{/* Add more buttons for other languages as needed */}
</div>
);
}
changeLanguage will only (maybe not properly work on client).... please to a language switcher like this: https://github.com/i18next/next-app-dir-i18next-example-ts/blob/main/app/%5Blng%5D/components/Footer/FooterBase.tsx#L18 That way the appropriate translations will be loaded correctly...
Thank you, finally I found it
<Footer lng={lng} path="/client-page" />
If I have a hundred pages, it is not a good idea to manually add path="/pathname". Is there a way to automatically add /pathname?
I tried adding a button myself and using href to point out lng and pathname
const pathname = usePathname()
href="{lng}{pathname}"
and the like, but there will be some strange situations such as http://localhost:3000/de/de/
Is there a way?
In addition, I use button and href to point out lng and pathname. Is this a good idea? Or is it stupid?
Let me know where should I ask this type of question? I don't want to mess it up, Thanks
Since next-app-dir-i18next-example-ts is just an example... you could do whatever you want... Personally, if you start to manipulate the href on client side, you may need to check if the pathname already starts with a /language/ something similar to the middleware: https://github.com/i18next/next-app-dir-i18next-example-ts/blob/main/middleware.ts