Skip to content

Instantly share code, notes, and snippets.

@fwojciec
Created September 3, 2019 13:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fwojciec/9d56ef0d103cf0f511e2d035ca2e4062 to your computer and use it in GitHub Desktop.
Save fwojciec/9d56ef0d103cf0f511e2d035ca2e4062 to your computer and use it in GitHub Desktop.
How to build a multilingual website in Next.js #6
// 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