Created
September 3, 2019 13:46
-
-
Save fwojciec/dcdcf3f78fc665ed9e696db02688652f to your computer and use it in GitHub Desktop.
How to build a multilingual website in Next.js
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
// 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