言語の変更

Reactアプリの言語を変更する方法

概要

このガイドでは、Reactアプリの言語を変更する方法をご紹介します。

まだアプリにgt-reactを設定していない場合は、続ける前にクイックスタートガイドをご参照ください。

gt-reactを使ってアプリの言語を変更する方法は3つあります。

  1. useSetLocale()フックを使う方法
  2. <LocaleSelector>コンポーネントを使う方法
  3. useLocaleSelector()フックを使う方法

このガイドでは、これら3つの方法すべてについて解説します。

useSetLocale フックの使い方

useSetLocale フックは、アプリの言語を変更できるクライアントサイドのフックです。これは必ず GTProvider コンポーネント内で使用する必要があります。

import { useSetLocale } from 'gt-react';
export default function MyComponent() {
  const setLocale = useSetLocale();

  return <button onClick={() => setLocale('en')}>Set Locale</button>;
}

変更したいロケールを、useSetLocale フックが返すコールバック関数の引数として渡すだけです。

<LocaleSelector> コンポーネントの使い方

<LocaleSelector> コンポーネントは、アプリの言語を変更できるクライアントサイドのコンポーネントです。GTProvider コンポーネント内で使用する必要があります。

これは、プロジェクトで有効にしているすべてのロケールを表示し、ユーザーが別のロケールを選択できるシンプルなUIドロップダウンです。

import { LocaleSelector } from 'gt-react';

export default function MyComponent() {
  return <LocaleSelector />;
}

useLocaleSelector フックの使用

または、独自のロケールセレクターコンポーネントを作成したい場合は、useLocaleSelector フックを使用できます。

このフックは、現在のロケール、プロジェクトがサポートするロケールのリスト、および useSetLocale フックを返します。

以下は、useLocaleSelector フックを使用してカスタムロケールセレクターコンポーネントを作成する方法の例です。

import { useLocaleSelector } from 'gt-react';

function capitalizeLanguageName(language: string): string {
  if (!language) return '';
  return (
    language.charAt(0).toUpperCase() +
    (language.length > 1 ? language.slice(1) : '')
  );
}

export default function LocaleDropdown({ className }: { className?: string }) {
  // Retrieve the locale, locales, and setLocale function
  const { locale, locales, setLocale, getLocaleProperties } = useLocaleSelector();

  // Helper function to get the display name of a locale
  const getDisplayName = (locale: string) => {
    return capitalizeLanguageName(
      getLocaleProperties(locale).nativeNameWithRegionCode
    );
  };

  // If no locales are returned, just render nothing or handle gracefully
  if (!locales || locales.length === 0 || !setLocale) {
    return null;
  }

  return (
    <Select onValueChange={setLocale} defaultValue={locale}>
      <SelectTrigger>
        <SelectValue placeholder='Select language' />
      </SelectTrigger>
      <SelectContent className='z-[200!important]' position='popper'>
        <SelectGroup>
          {!locale && <SelectItem value='' />}

          {locales.map((locale) => (
            <SelectItem key={locale} value={locale} suppressHydrationWarning>
              {getDisplayName(locale)}
            </SelectItem>
          ))}
        </SelectGroup>
      </SelectContent>
    </Select>
  );
}

詳細については、APIリファレンスを参照してください。

次のステップ

このガイドはいかがですか?