next-rosetta
Version:
Next.js + Rosetta with native i18n support
39 lines (36 loc) • 1.42 kB
JavaScript
import React, { createContext, useContext, useRef } from 'react';
import { useRouter } from 'next/router';
import rosetta from 'rosetta';
/**
* Use <I18nProvider /> instead of this internal context.
*/
var I18nContext = createContext(null);
/**
* @example <caption>Simple</caption>
* const { t } = useI18n()
* const text = t("title")
* @example <caption>With types</caption>
* interface LocaleTable { title: string; }
* const { t } = useI18n<LocaleTable>()
* const text = t("title")
*/
function useI18n() {
var instance = useContext(I18nContext);
if (!instance) {
throw new Error("There was an error getting i18n instance from context");
}
return instance;
}
/**
* You probably want to add this at the root of your project. If you are using Next.js add it to `_app.tsx`.
*/
function I18nProvider(_a) {
var table = _a.table, children = _a.children;
var i18nRef = useRef(rosetta());
var _b = useRouter(), _c = _b.locale, locale = _c === void 0 ? "en" : _c, _d = _b.defaultLocale, defaultLocale = _d === void 0 ? "en" : _d;
i18nRef.current.set(locale !== null && locale !== void 0 ? locale : defaultLocale, table);
i18nRef.current.locale(locale);
return React.createElement(I18nContext.Provider, { value: i18nRef.current }, children);
}
export { I18nContext, I18nProvider, useI18n };
//# sourceMappingURL=next-rosetta.esm.js.map