Build a Multilingual Website in React using react-intl v4 in 2020 (1)
I found that most of the resources about react-intl
are outdated and the docs of react-intl
is quite ambiguous. Therefore, I will demo some components and functions of react-intl
after some trial and error to help other peoples who want to build a multilingual website.
We use create-react-app
in this article. Let’s make a new project called multilingual-website
:
npx create-react-app multilingual-website
First of all, we need to install the package by running command :
npm i react-intl --save
npm install @material-ui/core
We are using material-ui
for the ui component library.
Then, we can import IntlProvider
component from react-intl
and wrap
the react app with <IntlProvider>
to enable internationalization.
In App.js:
In IntlProvider
we can set some properties:
locale
: we need to tell IntlProvider
which locale is using.
messages
: object of translated strings in different languages.
To look up for the user’s locale, we can use navigator.language
and it will return user’s preferred locale.
In this demo, I restricted the locale should be zh
or en
.
At this moment, you click the button and nothing happened. We have to add the translated strings to the message
and add function to the Button
for switching languages. Then, we replace the plain text with react-intl
component to retrieve the string for the corresponding language.
We use useState
hook to store the locale and use Button
to change it. Also, we created two versions of translated strings in const messages
,in <IntlProvider/>
we give messages
props with correct locale messages object. Then, pass the key of that string as id in <FormattedMessage/>
.
Now, if we want to add a input field :
<TextField id=”standard-basic” label=”username” />
we want the label
show the correct text based on the locale, we should use injectIntl
function, it will inject intl
as props, then we can get the massages by calling intl.formatMessage({id:"XXXXXXX"})
:
We can also make some variables in message and inject the value based on the user interaction, e.g. greeting, we add 'homepage.greeting': 'Hello {name}'
to the messages, we can now inject value to {name}
. See the example code below:
Tips: Remember to check the Safari browser, you may need to import extra Polyfill to make it work fine in Safari.