Skip to content

Instantly share code, notes, and snippets.

@treckstar
Last active April 5, 2023 15:11
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 treckstar/472cf15f8fc983205f99277f6be0f771 to your computer and use it in GitHub Desktop.
Save treckstar/472cf15f8fc983205f99277f6be0f771 to your computer and use it in GitHub Desktop.
Class Based TypeScript React.Component - Locale Switcher
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;
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