Helpers
useLocaleSelector()
useLocaleSelectorフックのAPIリファレンス
概要
このフックは現在のロケール、ロケールのリスト、およびuseSetLocale()
フックを返します。
これは独自のロケールセレクターコンポーネントを作成する際の簡単な使用を目的としています。
独自に実装したくない場合は、代わりに<LocaleSelector>
コンポーネントを使用できます。
Reference
Returns
現在のロケール、ロケールのリスト、およびuseSetLocale()
フックを含むオブジェクト。
例
<LocaleSelector>
これは<LocaleSelector>
コンポーネントの実装例です。
export default function LocaleSelector({
locales: _locales,
...props
}: {
locales?: string[];
[key: string]: any;
}): React.JSX.Element | null {
// Get locale selector properties
const { locale, locales, setLocale, getLocaleProperties } = useLocaleSelector(
_locales ? _locales : undefined
);
// Get display name
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
{...props}
// Fallback to an empty string if currentLocale is undefined
value={locale || ''}
onChange={(e) => setLocale(e.target.value)}
>
{/* Optional fallback for when no locale is set */}
{!locale && <option value='' />}
{locales.map((locale) => (
<option key={locale} value={locale} suppressHydrationWarning>
{getDisplayName(locale)}
</option>
))}
</select>
);
}
注意事項
- このフックはクライアントサイドでのみ動作します。
- ロケール文字列について詳しくはこちらをご覧ください。
次のステップ
<LocaleSelector>
コンポーネントについて詳しく学ぶ。useLocale()
フックについて詳しく学ぶ。
このガイドはいかがですか?