next-rosetta
Version:
Next.js + Rosetta with native i18n support
50 lines (43 loc) • 1.82 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
var React = require('react');
var router = require('next/router');
var rosetta = require('rosetta');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
var rosetta__default = /*#__PURE__*/_interopDefaultLegacy(rosetta);
/**
* Use <I18nProvider /> instead of this internal context.
*/
var I18nContext = React.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 = React.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 = React.useRef(rosetta__default["default"]());
var _b = router.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__default["default"].createElement(I18nContext.Provider, { value: i18nRef.current }, children);
}
exports.I18nContext = I18nContext;
exports.I18nProvider = I18nProvider;
exports.useI18n = useI18n;
//# sourceMappingURL=next-rosetta.js.map