-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathuseEnhancedTo.ts
More file actions
56 lines (55 loc) · 2.01 KB
/
useEnhancedTo.ts
File metadata and controls
56 lines (55 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { useMemo } from "react"
import { type To, useSearchParams } from "react-router"
import type { Language } from "~/localization/resource"
/**
* Enhances the default to prop by adding the language to the search params and conditionally keeping the search params
* @param language The language to use over the search param language
* @param to The new location to navigate to
* @param keepSearchParams Whether to keep the search params or not
*
* @example
* ```tsx
* // override the language
* function Component(){
* const enhancedTo = useEnhancedTo({ language: "en", to: "/" })
* return <Link to={enhancedTo} /> // Will navigate to /?lng=en even if the current url contains a different lanugage
* }
*
* function Component(){
* const enhancedTo = useEnhancedTo({ to: "/" })
* return <Link to={enhancedTo} /> // Will navigate to /?lng=X where X is the current language in the url search params, or just to / if no language is found
* }
*
* function Component(){
* const enhancedTo = useEnhancedTo({ to: "/", keepSearchParams: true })
* return <Link to={enhancedTo} /> // Will navigate to /?params=from_the_url_search_params&lng=en
* }
* ```
*/
export const useEnhancedTo = ({
language,
to,
keepSearchParams,
}: {
language?: Language
to: To
keepSearchParams?: boolean
}) => {
const [params] = useSearchParams()
const { lng, ...searchParams } = Object.fromEntries(params.entries())
// allow language override for language switcher or manually setting the language in specific cases
const lang = language ?? lng
const newSearchParams = new URLSearchParams(searchParams)
const searchString = newSearchParams.toString()
const hasSearchParams = searchString.length > 0
const appendSearchParams = lang || hasSearchParams
const newPath = useMemo(
() =>
to +
(appendSearchParams
? `?${keepSearchParams && hasSearchParams ? `${searchString}${lang ? "&" : ""}` : ""}${lang ? `lng=${lang}` : ""}`
: ""),
[to, appendSearchParams, keepSearchParams, hasSearchParams, searchString, lang]
)
return newPath
}