A library to use react-intl along with a mobx store.
src/LocaleStore.js
is a mobx store that contains the locale data and persists the
locale to the browser locale storage.
The store expects the default locale and the translations for all supported locales as argument.
It is possible to format messages without using react-mobx by calling the formatMessage
function from the store.
This can be especially useful when using localized data in other stores (pass the locale store as a constructor of other stores).
The selected locale is persisted to the LocalStorage if it exists.
src/MobxIntlProvider.js
: Creates the I18n provider for mobx. Note that it relies on IntlProvider
from react-intl
.
This component takes the locale store as prop.
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
is implemented in the LocaleStore
for this case.
An example of usage is provided in examples/simple-app
.
To run this create-react-app
project, run the following commands (yarn
can be replaced by npm
)
yarn install
yarn start
To have internationalization (i18n) working with react, mobx and react-intl, we need to:
- Create a store for the i18n data (locale used and locale data)
- Uhe use a custom provider to provide internationalization from the mobx store.
- Inject the provider to UI components.
- Use the provided code.
We create two files to maintain locale data:
./translations/en.js
and ./translations/de.js
provide translations for English and German.
./Toolbar.js
is the component used to switch from one language to another.
./Home.js
is a UI component that uses i18n to display texts.
In ./App.js
we finally wrap up all components.
The app is initialized initialized with the Provider and shows the Home
component.