Namespaced i18next localization in react with no tears
Switch branches/tags
Nothing to show
Clone or download
Latest commit c356660 Nov 30, 2018

README.md

NS react-i18next

npm package gzip bundle size codecov Build Status

Manage i18next namespaces with a power of react v16 context

Installation

Available as npm package.

npm install ns-react-i18next

Add global provider to the root of your app

import * as i18n from 'i18next';
import { I18NextProvider } from 'ns-react-i18next'

i18n
  .use(LanguageDetector)
  .init({
    resources: translations,
    fallbackLng: 'en',
    debug: true,
    defaultNS: 'common', // this namespace will be used if no namespace shared via context
    fallbackNS: 'common',
  });

ReactDom.render(
  <I18NextProvider i18n={i18n}>
    <App />
  </I18NextProvider>,
  document.getElementById('root')
)

Usage

Use another provider to share namespace between components sub-tree. Any <Translate> component under this provider will render translated string of shared namespace + children string. Note that when the language will be changed (with a help of i18n.changeLanguage()) - every translate will rerender by itself.

import { Translate, NamespaceProvider } from 'ns-react-i18next'

<NamespaceProvider ns="specificNs">
  // specificNs:some_complex_structure
  <p> <Translate interpolate={{ key: 'value' }}> some_complex_structure </Translate> </p>
  <p> <Translate> something_specific </Translate> </p> // specificNs:something_specific
</NamespaceProvider>

Even possible to share namespace for several routes.

<NamespaceProvider ns="customers">
  <Route path="/customers" component={CustomersList} />
  <Route path="/customers/:id" component={ManageCustomer} />
</NamespaceProvider>

There any Translate of CustomersList, ManageCustomer and thiers sub-components and sub-routes of take the 'customers' namespace.