nuxt-modules / i18n

I18n module for Nuxt
https://i18n.nuxtjs.org
MIT License
1.75k stars 483 forks source link

feat: experimental feature `switchLocalePathLinkSSR` with `<SwitchLocalePathLink>` component #2838

Closed BobbieGoede closed 8 months ago

BobbieGoede commented 8 months ago

๐Ÿ”— Linked issue

โ“ Type of change

๐Ÿ“š Description

Resolves #2798

This adds a component SwitchLocalePathLink which is not much different from passing switchLocalePath to NuxtLink except the resulting link is wrapped in comments <!--nuxt-i18n-slp-[locale]-->...<!--/nuxt-i18n-slp-->.

While setI18nParams currently works, it actually doesn't render the correct links during SSR depending on when and where it is used (as a warning describes in the docs), I have added an experimental feature that aims to resolve this.

The following functionality is enabled with the experimental.switchLocalePathLinkSSR property:

The setI18nParams is changed to use a useState ref instead of the nuxtI18n meta property on the route, this would normally cause a hydration mismatch (lang switcher rendered before setI18nParams is called, while the client will have the correct data at hydration) which is why we couldn't use this before.

Using the wrapping comments to find the links with their locale in the rendered DOM at the end of SSR, the URL is replaced with an up to date localized path returned from switchLocalePath.

The implementation feels hacky to me but it seems to work fine, if there is a better way to do this please let me know!

๐Ÿ“ Checklist

nuxt-studio[bot] commented 8 months ago

Live Preview ready!

Name Edit Preview Latest Commit
i18n Edit on Studio โ†—๏ธŽ View Live Preview 2508a27dc9f3a4ee8a98589dc9a56e39008fda62