Home

Awesome

react-mobx-translatable

Make React components translatable using MobX. Can be used both on the server (SSR) and in the browser.

Note: This plugin depends on mobx-react features that are currently marked as experimental: Provider and inject.

Build Status Dependency Status devDependency Status

Installation

npm install react-mobx-translatable

Usage

Checklist (see the example for more details)

Methods

init(injectFn)

Method receives injectFn - function that maps the i18n object from the store

translatable(Component|String[])

Method can receive either an array of strings or a React component.

In both cases, the wrapped component will also be an observer. If using with other decorators, translatable should be the innermost one.

Example

The example assumes you're using the following:

This is however not a requirement.

Initialize store, i18n, and translatable

import {observable} from 'mobx';
import i18n from 'i18n-harmony';
import {init} from 'translatable';

const defaultLocale = 'en'; // Can be based on browser language or user selection (localStorage, cookies)

const store = {
  i18n: observable({locale: defaultLocale})
};

// For details, see i18n-harmony: https://github.com/DarkoKukovec/i18n-harmony
i18n.init({
  translations: {
    en: {hello: 'Hello world!'}
  }
});

init((store) => ({i18n: store.i18n}));

Wrap your React components inside of the Provider component and pass it the store

import {Provider} from 'mobx-react';
import store from './store';

ReactDOM.render(<Provider {...store}>
  <Router {...renderProps} />
</Provider>, document.getElementById('app'));

Translatable component

import {Component} from 'react';
import {translatable} from 'translatable';

@translatable
export default class MyComponent extends Component {
  render() {
    return <div>{this.t('hello')}</div>
  }
}

has method

import {Component} from 'react';
import {translatable} from 'translatable';

@translatable
export default class MyComponent extends Component {
  render() {
    return <div>{this.has('hello') && this.t('hello')}</div>
  }
}

Changelog

v1.2.0

v1.1.0

v1.0.0

License

MIT License