Blog>
Snippets

Using useRouter Hook for Locale Switching

Provide an example of using Next.js useRouter hook to switch between locales manually via a language selector component.
import { useRouter } from 'next/router';

export default function LanguageSelector() {
  const router = useRouter();

  const switchLocale = (locale) => {
    const { pathname, query, asPath } = router;
    router.push({ pathname, query }, asPath, { locale });
  };

  return (
    <div>
      <button onClick={() => switchLocale('en')}>English</button>
      <button onClick={() => switchLocale('fr')}>Français</button>
      <button onClick={() => switchLocale('es')}>Español</button>
    </div>
  );
}
This JavaScript function component uses the useRouter hook from Next.js to switch between different locales. It defines a function 'switchLocale' that updates the locale using the router.push method, which navigates to the same page with the specified locale while keeping the current pathname and query parameters. HTML buttons are used to manually trigger the locale switch for English, French, and Spanish.
/* Add some simple styling for buttons */
button {
  margin-right: 8px;
  cursor: pointer;
}
This is the CSS snippet to style the buttons in the LanguageSelector component. It adds a right margin and changes the cursor to a pointer on hover to indicate that the buttons are clickable.