react-intlayer
Version:
Easily internationalize i18n your React applications with type-safe multilingual content management.
46 lines (43 loc) • 1.95 kB
JavaScript
'use client';
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
const require_client_IntlayerProvider = require('./IntlayerProvider.cjs');
let _intlayer_core_interpreter = require("@intlayer/core/interpreter");
let react = require("react");
//#region src/client/useI18n.ts
/**
* Hook that provides a translation function `t()` for accessing nested content by key.
* This hook mimics the pattern found in libraries like i18next, next-intl, and vue-i18n.
*
* @param namespace - The dictionary key to scope translations to
* @param locale - Optional locale override. If not provided, uses the current context locale
* @returns A translation function `t(key)` that returns the translated content for the given key
*
* @example
* ```tsx
* const t = useI18n('IndexPage');
* const title = t('title'); // Returns translated string for 'IndexPage.title'
* const nestedContent = t('section.subtitle'); // Returns 'IndexPage.section.subtitle'
* // For attributes like `aria-label`, use `.value` to get the plain string
* const ariaLabel = t('button.ariaLabel').value; // 'Close modal'
* ```
*/
const useI18n = (namespace, locale) => {
const { locale: currentLocale } = (0, react.useContext)(require_client_IntlayerProvider.IntlayerClientContext) ?? {};
const localeTarget = (0, react.useMemo)(() => locale ?? currentLocale, [currentLocale, locale]);
const dictionaryContent = (0, react.useMemo)(() => (0, _intlayer_core_interpreter.getIntlayer)(namespace, localeTarget), [namespace, localeTarget]);
const t = (path) => {
if (!path) return dictionaryContent;
const pathArray = path.split(".");
let current = dictionaryContent;
for (const key of pathArray) {
current = current?.[key];
if (current === void 0) return dictionaryContent;
}
return current;
};
return t;
};
//#endregion
exports.useI18n = useI18n;
//# sourceMappingURL=useI18n.cjs.map