Helpers
useLocaleSelector()
API Reference for the useLocaleSelector hook
Overview
This hook returns the current locale, the list of locales, and the useSetLocale()
hook.
This is meant for easy use when creating your own locale selector component.
If you don't want to implement your own, you can use the <LocaleSelector>
component instead.
Reference
Returns
An object containing the current locale, the list of locales, and the useSetLocale()
hook.
Examples
<LocaleSelector>
This is the example implementation of the <LocaleSelector>
component.
export default function LocaleSelector({
locales: _locales,
...props
}: {
locales?: string[];
[key: string]: any;
}): React.JSX.Element | null {
// Get locale selector properties
const { locale, locales, setLocale } = 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>
);
}
Notes
- This hook is client-side only.
- Learn more about locale strings here.
Next Steps
- Learn more about the
<LocaleSelector>
component. - Learn more about the
useLocale()
hook.