UNPKG

@translata/react

Version:

React integration for translata: The Composable Translation Utility

66 lines (65 loc) 2.1 kB
var __read = (this && this.__read) || function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; }; import React, { createContext, useContext, useState, useMemo, } from 'react'; /** * Create a translator provider, including hooks to consume the translation context. * * @param defaultLocale Default locale. * @param factory Translator factory. */ export function createTranslatorProvider(defaultLocale, factory) { var Context = createContext({ translator: null, locale: null, setLocale: null, }); /** * The Translator Provider. * * @param props */ function Provider(props) { var _a = __read(useState(defaultLocale), 2), locale = _a[0], setLocale = _a[1]; var translator = useMemo(function () { return factory(locale); }, [locale]); var state = useMemo(function () { return ({ translator: translator, locale: locale, setLocale: setLocale, }); }, [translator, locale]); return React.createElement(Context.Provider, { value: state }, props.children); } /** * Use the current translator from context. */ function useTranslator() { return useContext(Context).translator; } /** * Use the current locale from context. */ function useLocale() { return useContext(Context).locale; } /** * Use the locale setter from context, this allows you to change * the default locale on context level. */ function useSetLocale() { return useContext(Context).setLocale; } return Object.assign(Provider, { useLocale: useLocale, useSetLocale: useSetLocale, useTranslator: useTranslator }); }