i18n-for-react

Modern translation module for React.

Usage no npm install needed!

<script type="module">
  import i18nForReact from 'https://cdn.skypack.dev/i18n-for-react';
</script>

README

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,
    createI18nHook
    __x,
    __xmf,
    __xn
};

Description of this methods you can find in Documentation.

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

createI18nProvider

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'
    }
);

I18nProvider

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>

useI18n

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`;
}

rprintf()

Format string with wrappers.

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

__x()

Same as __(), but for JSX.

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

__xmf()

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/>])

__xn()

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/>])