Skip to content

Instantly share code, notes, and snippets.

@fwojciec
Created September 3, 2019 13:46
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/dcdcf3f78fc665ed9e696db02688652f to your computer and use it in GitHub Desktop.
Save fwojciec/dcdcf3f78fc665ed9e696db02688652f to your computer and use it in GitHub Desktop.
How to build a multilingual website in Next.js
// components/LocaleSwitcher.tsx
import React from 'react'
import { useRouter } from 'next/dist/client/router'
import { locales, languageNames } from '../translations/config'
import { LocaleContext } from '../context/LocaleContext'
const LocaleSwitcher: React.FC = () => {
const router = useRouter()
const { locale } = React.useContext(LocaleContext)
const handleLocaleChange = React.useCallback(
(e: React.ChangeEvent<HTMLSelectElement>) => {
const regex = new RegExp(`^/(${locales.join('|')})`)
router.push(router.pathname, router.asPath.replace(regex, `/${e.target.value}`))
},
[router]
)
return (
<select value={locale} onChange={handleLocaleChange}>
{locales.map(locale => (
<option key={locale} value={locale}>
{languageNames[locale]}
</option>
))}
</select>
)
}
export default LocaleSwitcher
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment