言語切り替え機能の構築
ユーザーが任意のページで言語を切り替えられるようにする
課題
ユーザーが/en/products/123などの特定のページにいて、同じページを別の言語で表示したい場合、言語切り替え(例:「Français」)をクリックすると、対応する商品ページではなくホームページ(/fr/)に戻されることが多く、ワークフローが中断され、再度ナビゲートする必要が生じます。
解決策
現在のURLパス名を読み取るクライアントコンポーネントを作成します。パス内の現在の言語セグメントを置き換えることで、サポートされている他のすべての言語のリンクリストを生成します。また、クリック時に設定cookieを設定し、今後の訪問時に選択が記憶されるようにします。
手順
1. 言語設定を定義する
i18n.config.tsファイルに、ロケールのリストと使用するcookieの名前が含まれていることを確認してください。
// i18n.config.ts
export const locales = ['en', 'es', 'fr'];
export const defaultLocale = 'en';
export const localeCookieName = 'NEXT_LOCALE';
2. 言語切り替えコンポーネントを作成する
新しいファイル(例:app/components/LanguageSwitcher.tsx)を作成します。usePathnameなどのフックを使用するには、クライアントコンポーネントである必要があります。
// app/components/LanguageSwitcher.tsx
'use client';
import { usePathname } from 'next/navigation';
import Link from 'next/link';
import { locales, localeCookieName } from '@/i18n.config';
export default function LanguageSwitcher() {
const pathname = usePathname();
// This function sets the cookie
const setLocaleCookie = (locale: string) => {
document.cookie = `${localeCookieName}=${locale}; path=/; max-age=31536000; samesite=lax`;
};
// This function strips the current locale from the path
const getRedirectedPath = (locale: string) => {
if (!pathname) return '/';
const segments = pathname.split('/');
segments[1] = locale; // The locale is always the first segment
return segments.join('/');
};
return (
<div>
{locales.map((locale) => (
<Link
key={locale}
href={getRedirectedPath(locale)}
onClick={() => setLocaleCookie(locale)}
style={{
display: 'inline-block',
padding: '0.5rem',
textDecoration: 'underline',
}}
>
{locale.toUpperCase()}
</Link>
))}
</div>
);
}
3. レイアウトに切り替え機能を追加する
新しいコンポーネントをルートレイアウトファイル(app/[lang]/layout.tsx)にインポートして配置します。これにより、すべてのページで表示されるようになります。
// app/[lang]/layout.tsx
import LanguageSwitcher from '@/app/components/LanguageSwitcher';
export async function generateStaticParams() {
// This tells Next.js to pre-render 'en', 'es', and 'fr'
return [{ lang: 'en' }, { lang: 'es' }, { lang: 'fr' }];
}
export default function RootLayout({
children,
params,
}: {
children: React.ReactNode;
params: { lang: string };
}) {
return (
<html lang={params.lang}>
<body>
<header>
{/* Add the switcher to your header or nav */}
<LanguageSwitcher />
</header>
<main>{children}</main>
</body>
</html>
);
}
これで、ユーザーが/es/products/123にいて「EN」をクリックすると、コンポーネントは新しいパスを/en/products/123として計算し、NEXT_LOCALE cookieを「en」に設定します。