This example React
project shows how to fetch i18n
messages - to be used in storybook
with storybook-addon-intl
or just plain react-intl
- from a json
REST API
.
Run: npm i && npm run storybook
, then select the Button > with FormattedMessage story and use the LOCALES bar to switch the active locale; the text of the button should be correctly translated.
This example setup also works perfectly when building storybook
with npm run build-storybook
: after building you can test it all works correctly by running npm run serve-storybook
.
This app was bootstrapped with Create React App, you can find the most recent version of the Create React App guide here) and the following packages were integrated:
- storybook - Interactive development & testing environment for React, React-Native, Vue UI components. Installed in one minute using the official
CLI tool
. - storybook-addon-intl - Addon to provide a locale switcher and react-intl for storybook.
- react-intl - Internationalize React apps. This library provides React components and an API to format dates, numbers, and strings, including pluralization and handling translations. This one is installed automatically if you use
storybook-addon-intl
.
-
Look up
./scripts/fetch-messages.js
to see howisomorphic-fetch
is used to fetch thejson
of the messages. See the comments there showing how to quickly replace/remove the sample data and insert your realAPI
url. For simplicity's sake, we assume you can call anAPI
endpoint that returns messages for all locales at once. -
Look up
.storybook/config.js
too see howstorybook-addon-intl
and the locale data is configured, the comments there show you where to set your supported locales and load the required localisation data.
This is how we accomplish it in this example:
- the user runs:
npm run storybook
npm
runs the task:prestorybook
- the
prestorybook
tasks runs the task:fetch-messages
- the
fetch-messages
task fetches the messages fromAPI
and saves them to thestatic
folder. - the
storybook
task is run. storybook
loads the configuration files:.storybook/addons.js
and.storybook/config.js
.storybook
starts its development server ... all done.