Merged in feature/refactor-lang (pull request #387)
feat: SW-238 Avoid prop drilling of lang Approved-by: Michael Zetterberg
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
# Internationalization
|
||||
|
||||
## The `lang` route parameter
|
||||
|
||||
All page paths starts with a language parameter, e.g. `/sv/utforska-scandic/wi-fi`.
|
||||
|
||||
### Get the language in a client component
|
||||
|
||||
We have a hook called `useLang` that directly returns the `lang` parameter from the path.
|
||||
|
||||
### Get the language in a server component
|
||||
|
||||
In order to not prop drill that all the way from a page we use React's `cache` in a way that resembles React`s context, but on the server side.
|
||||
|
||||
For this to work we must set the language with `setLang` on all root layouts and pages, including pages in parallel routes. Then we can use `getLang` in the components where we need the language.
|
||||
|
||||
This was inspired by [server-only-context](https://github.com/manvalls/server-only-context)
|
||||
@@ -0,0 +1,22 @@
|
||||
import { cache } from "react"
|
||||
|
||||
import { Lang } from "@/constants/languages"
|
||||
|
||||
const getRef = cache(() => ({ current: Lang.en }))
|
||||
|
||||
/**
|
||||
* Set the language for the current request
|
||||
*
|
||||
* It works kind of like React's context,
|
||||
* but on the server side, per request.
|
||||
*
|
||||
* @param newLang
|
||||
*/
|
||||
export const setLang = (newLang: Lang) => {
|
||||
getRef().current = newLang
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the global language set for the current request
|
||||
*/
|
||||
export const getLang = () => getRef().current
|
||||
Reference in New Issue
Block a user