Created
September 3, 2019 13:37
-
-
Save fwojciec/9d56ef0d103cf0f511e2d035ca2e4062 to your computer and use it in GitHub Desktop.
How to build a multilingual website in Next.js #6
This file contains 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
// context/LocaleContext.tsx | |
import React from 'react' | |
import { useRouter } from 'next/dist/client/router' | |
import { Locale, isLocale } from '../translations/types' | |
interface ContextProps { | |
readonly locale: Locale | |
readonly setLocale: (locale: Locale) => void | |
} | |
export const LocaleContext = React.createContext<ContextProps>({ | |
locale: 'en', | |
setLocale: () => null | |
}) | |
export const LocaleProvider: React.FC<{ lang: Locale }> = ({ lang, children }) => { | |
const [locale, setLocale] = React.useState(lang) | |
const { query } = useRouter() | |
// store the preference | |
React.useEffect(() => { | |
if (locale !== localStorage.getItem('locale')) { | |
localStorage.setItem('locale', locale) | |
} | |
}, [locale]) | |
// sync locale value on client-side route changes | |
React.useEffect(() => { | |
if (typeof query.lang === 'string' && isLocale(query.lang) && locale !== query.lang) { | |
setLocale(query.lang) | |
} | |
}, [query.lang, locale]) | |
return <LocaleContext.Provider value={{ locale, setLocale }}>{children}</LocaleContext.Provider> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment