Connectors between mobx-react and react-intl
npm install mobx-react-intlA library to use react-intl along with a mobx store for the selected locale with typescript support.



Since an example is worth a thousand words.
You can see this example running on Stackblitz
``javascript
import React, { Component } from 'react';
import { render } from 'react-dom';
import { Provider, inject, observer } from "mobx-react";
import { MobxIntlProvider, LocaleStore } from "mobx-react-intl";
import {addLocaleData, injectIntl, FormattedMessage} from "react-intl";
import enLocale from 'react-intl/locale-data/en';
import deLocale from 'react-intl/locale-data/de';
addLocaleData([...deLocale, ...enLocale]);
const translations = {
en: {
hello: "Hello",
world: "World"
},
de: {
hello: "Hallo",
world: "Wereld"
}
}
// Internationalization
const localeStore = new LocaleStore("en", translations);
const store = {
locale: localeStore, // The locale store has to be called locale.
};
const _Home = ({intl: {formatMessage}, locale}) =>
const App = () =>
render(
`
LocaleStore is a mobx store that contains the locale data and persists the
locale to the browser LocalStorage (if it exists).
The store expects the default locale and the translations for all supported locales as arguments.
MobxIntlProvider.js: Creates the I18n provider for mobx. Note that it relies on IntlProvider from react-intl.
This component has the same interface as IntlProvider
except that the locale and messages attributes are injected through mobx.
It is possible to also use the i18n without being in the react scope. For example when initializing a
store that needs locale data, just pass the locale store as a prop. You can see that a formatMessage method LocaleStore
is implemented in the for this case.
A running example with some file structure is provided in examples/simple-app.
project, run the following commands (yarn can be replaced by npm)`bash
yarn install
yarn start
`$3
To have internationalization (i18n) working with react, mobx and react-intl,
we need to:
1. Create a store for the i18n data (locale used and locale data)
2. Uhe use a custom provider to provide internationalization from the mobx store.
3. Inject the provider to UI components.
4. Use the provided code.
$3
We create two files to maintain locale data:
./translations/en.js and ./translations/de.js provide translations for English and German.
Language Switcher
./Toolbar.js is the component used to switch from one language to another. Home
./Home.js is a UI component that uses i18n to display texts.
Application initializer
In
./App.js we finally wrap up all components. The app is initialized initialized with the Provider and shows the
Home` component.