Last active
April 5, 2023 15:11
-
-
Save treckstar/472cf15f8fc983205f99277f6be0f771 to your computer and use it in GitHub Desktop.
Class Based TypeScript React.Component - Locale Switcher
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
import React from 'react'; | |
import { useRouter } from 'next/router'; | |
type Props = { | |
locales: string[]; | |
currentLocale: string; | |
}; | |
class LocaleSwitcher extends React.Component<Props> { | |
private handleLocaleChange = (event: React.ChangeEvent<HTMLSelectElement>) => { | |
const newLocale = event.target.value; | |
const { locales } = this.props; | |
if (newLocale !== this.props.currentLocale && locales.includes(newLocale)) { | |
const router = useRouter(); | |
router.push(router.pathname, router.asPath, { locale: newLocale }); | |
} | |
}; | |
render() { | |
const { locales, currentLocale } = this.props; | |
return ( | |
<select value={currentLocale} onChange={this.handleLocaleChange}> | |
{locales.map(locale => ( | |
<option key={locale} value={locale}> | |
{locale.toUpperCase()} | |
</option> | |
))} | |
</select> | |
); | |
} | |
} | |
export default LocaleSwitcher; |
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
import React, { Component } from 'react'; | |
import Link from 'next/link'; | |
import { withRouter, SingletonRouter } from 'next/router'; | |
type Locale = { | |
locale: string; | |
label: string; | |
}; | |
type Props = { | |
locales: Locale[]; | |
router: SingletonRouter; | |
}; | |
class LocaleMenu extends Component<Props> { | |
render() { | |
const { locales, router } = this.props; | |
const { pathname, query } = router; | |
return ( | |
<nav> | |
<ul> | |
{locales.map(locale => ( | |
<li key={locale.locale}> | |
<Link href={{ pathname, query }} locale={locale.locale}> | |
<a className={locale.locale === router.locale ? 'active' : ''}>{locale.label}</a> | |
</Link> | |
</li> | |
))} | |
</ul> | |
</nav> | |
); | |
} | |
} | |
export default withRouter(LocaleMenu); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment