Skip to content

TrigenSoftware/i18n-for-react

Repository files navigation

i18n-for-react

NPM version Dependencies status Build status Coverage status Dependabot badge Documentation badge

Modern translation module for React.

Install

npm i i18n-for-react
# or
yarn add i18n-for-react

API

Module exposes next API:

// all i18n-for-browser exports, plus:
export {
    I18nMethods,
    I18nProviderConfig,
    I18nProviderProps,
    I18nContextPayload,
    rprintf,
    createI18nProvider,
    __x,
    __xmf,
    __xn
};

Description of this methods you can find in Documentation.

Basic API is same as in i18n-for-browser module.

Create I18nContext and I18nProvider with given methods.

Usage example
/**
 * Basic example 
 */
const {
    /**
     * Config and methods provider.
     */
    I18nProvider,
    /**
     * Context with config and methods.
     */
    I18nContext,
    /**
     * Hook to recieve config and methods.
     */
    useI18n
} = createI18nProvider(
    /**
     * Methods for binding and providing.
     */
    {
        __,
        __x
    },
    /**
     * Config defaults.
     */
    {
        /* ... */
        cookieName: 'yourcookiename'
    }
);

Configurator and provider of i18n instance.

Usage example
/**
 * Root context configuration
 */
<I18nProvider
    locale='en'
    locales={{
        en: {/* ... */},
        ru: {/* ... */}
    }}
>
    {/* ... */}
</I18nProvider>
/**
 * Fork context
 */
<I18nProvider
    locale='en'
    locales={{
        en: {/* ... */},
        ru: {/* ... */}
    }}
>
    {/* ... */}
    <I18nProvider
        locales={{
            en: {/* ... */},
            ru: {/* ... */}
        }}
    >
        {/* ... */}
    </I18nProvider>
</I18nProvider>

Hook to recieve config and methods.

Usage example
/**
 * Basic example 
 */
function SomeComponent() {
    const {
        __
    } = useI18n();

    return __`cat`;
}
/**
 * Fork instance
 */
function SomeComponent() {
    const {
        __
    } = useI18n({
        locales: /* ... */
    });

    return __`cat`;
}

Format string with wrappers.

Usage example
/**
 * Wrap with React-elements
 */
rprintf('Hi, <>John</>!', [<b/>])
/**
 * or handle with functions
 */
rprintf('Hi, <>John</>!', [_ => `<b>${_}</b>`])

Same as __(), but for JSX.

Usage example
/**
 * Same as `__()`
 */
__x('Hi, %s!', 'John')
/**
 * And with wrappers
 */
__x('Hi, <>%s</>!', 'John', [<b/>])

Same as __mf(), but for JSX.

Usage example
/**
 * Same as `__mf()`
 */
__xmf('Hi, {username}!', { username: 'John' })
/**
 * And with wrappers
 */
__xmf('Hi, <>{username}</>!', { username: 'John' }, [<b/>])

Same as __n(), but for JSX.

Usage example
/**
 * Same as `__xn()`
 */
__xn('I have %s cats.', 2)
/**
 * And with wrappers
 */
__xn('I have <>%s</> cats.', 2, [<b/>])