Created
January 19, 2022 12:41
-
-
Save darioielardi/5184063f807d0834b6847e9693b8ea42 to your computer and use it in GitHub Desktop.
nextjs i18n
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useRouter } from 'next/router'; | |
export const locales = ['it', 'en'] as const; | |
export type Locale = typeof locales[number]; | |
export const isLocale = (locale: string): locale is Locale => { | |
return (locales as unknown as string[]).includes(locale); | |
}; | |
export type LocalizedValue<T> = { [key in Locale]: T }; | |
export const useLocale = (): Locale => { | |
const router = useRouter(); | |
return router.locale && isLocale(router.locale) ? router.locale : 'en'; | |
}; | |
export const useIntl = () => { | |
const router = useRouter(); | |
const locale = useLocale(); | |
const setLocale = (value: string) => { | |
if (isLocale(value) && value !== locale) { | |
document.cookie = `NEXT_LOCALE=${locale};path=/`; | |
router.replace(router.pathname, router.asPath, { locale: value }); | |
} | |
}; | |
return { | |
locale, | |
setLocale, | |
}; | |
}; | |
export type Txs< | |
BaseDef extends Record<string, unknown>, | |
Def = { [key in keyof BaseDef]: BaseDef[key] } | |
> = { | |
en: BaseDef; | |
} & LocalizedValue<Def>; | |
export const useTxs = <T extends Record<string, unknown>>(txs: Txs<T>): T => { | |
const locale = useLocale(); | |
return txs[locale]; | |
}; | |
export const createTxs = <T extends Record<string, unknown>>(def: Txs<T>) => { | |
return () => useTxs(def); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment