next-translate
next-translate copied to clipboard
How to change the language without adding /fr /en /de to the url?
Hi there, I work on a web application built with Next.js.
Some pages are clearly fitting next-translate or next-i18next + Next.js philosophy: internationalization is URL based. Like /fr/blog /en/blog.
But part of the app is actually a subapp where you login and you want to allow the user to change the language without having the URL to update (youtube.com like). So I would most probably store the user language preference somewhere (cookies..).
But then I haven't found a way to update the language of the page without having the URL being modified (not in next-translate, not in next-i18next).
I've tried shallow routing, I've tried to force the as= of links. Nothing works.
Is there any way to do so? Or is my only way to just roll with react-i18next and inline all json files in the bundle?
Thanks!
You can use the DynamicNamespaces component wrapped with a I18nProvider with the custom language. And you need to save this language in your way... (state / cookie / localstorage...)
Ex:
<I18nProvider lang="es">
<DynamicNamespaces namespaces={['dynamic']} fallback="Loading...">
<Trans i18nKey="dynamic:example-of-dynamic-translation" />
</DynamicNamespaces>
</I18nProvider>
Hey there, just wanted to say thanks, this definitely helped me a lot today :)
I have one bug actually is that updating the lang attribute of the provider does not trigger a re-render, not sure why yet.
@vvo As a workaround try to add the prop key={lang}
to I18Provider to force to remounting all the content (not just rerender). DynamicNamespaces right now is loading the namespaces only when namespaces change:
https://github.com/vinissimus/next-translate/blob/master/src/DynamicNamespaces.tsx#L30
Feel free to add a PR with the lang as dependency of this useEffect.
I will be back soon with the library βΊοΈ, I had an accident and I have been in the hospital for some time.
Is there some example to do the same thing? I can not find anything clear about this, Just as recommendations, I saw that this use case is mentioned on some issues reports, it would be great to make an example. thanks so much!
@fernandoamz maybe this help https://github.com/vinissimus/next-translate/discussions/681#discussioncomment-1286092
I had the same issue as @vvo, I realised ctx
.locale
can be set to whichever locale you want in your ServerSideProps which helps. I don't know why the front page documentation doesn't mention this but its useful. Not every app uses the URL to set their locale.
Original thread: https://github.com/vinissimus/next-translate/discussions/445#discussioncomment-2178314
It would be good to have How to change the language mention that the ctx.locale can also be set for those using databases to persist user's language choice