UNPKG

react-intlayer

Version:

Easily internationalize i18n your React applications with type-safe multilingual content management.

58 lines (55 loc) 1.77 kB
'use client'; import { setLocaleInStorage } from "./useLocaleStorage.mjs"; import { IntlayerClientContext } from "./IntlayerProvider.mjs"; import { internationalization } from "@intlayer/config/built"; import { useCallback, useContext } from "react"; //#region src/client/useLocale.ts /** * Client-side hook to get the current locale and related locale management functions. * * @param props - Optional properties for the hook. * @returns An object containing the current locale, default locale, available locales, and a function to update the locale. * * @example * ```tsx * import { useLocale } from 'react-intlayer'; * * const LocaleSwitcher = () => { * const { locale, setLocale, availableLocales } = useLocale(); * * return ( * <select value={locale} onChange={(e) => setLocale(e.target.value)}> * {availableLocales.map((loc) => ( * <option key={loc} value={loc}>{loc}</option> * ))} * </select> * ); * }; * ``` */ const useLocale = ({ isCookieEnabled, onLocaleChange } = {}) => { const { defaultLocale, locales: availableLocales } = internationalization ?? {}; const { locale, setLocale: setLocaleState, isCookieEnabled: isCookieEnabledContext } = useContext(IntlayerClientContext) ?? {}; return { locale, defaultLocale, availableLocales, setLocale: useCallback((locale) => { if (!availableLocales?.map(String).includes(locale)) { console.error(`Locale ${locale} is not available`); return; } setLocaleState(locale); setLocaleInStorage(locale, isCookieEnabled ?? isCookieEnabledContext ?? true); onLocaleChange?.(locale); }, [ availableLocales, onLocaleChange, setLocaleState, isCookieEnabled ]) }; }; //#endregion export { useLocale }; //# sourceMappingURL=useLocale.mjs.map