What is React Intl?
React Intl is a powerful tool within the FormatJS internationalization library suite. It supports for over 150 languages and extensive documentation to guide you through implementation. Built upon JavaScript's i18n API, React Intl offers enhanced functionalities and components, including dynamic language loading through React Context and higher-order components.
Get started:
1. Create a project
Following the instruction bellow:
- Create a new React project using:
npx create-react-app i18n-sample-code
cd i18n-sample-code
- Start the server with
npm start
oryarn start
. - The browser will be loaded up with localhost:3000
- Then install React Intl with
npm i -S react-intl
Note: I use MUI for this project, you can install it or not. npm install @mui/material
2. How to use
- Workflow application
To make the project clearly, the bellow is the source tree. As you can see I defined 2 languages: English and Japanese. Besides, I created a file named i18n.js to configure intl in the project.
- Configure the index.js file
- Detect the user’s preferred languages
Normally, users will have defined their preferred language settings in their browsers. Currently, most of browsers have a navigator.language object and this can be used to obtain the user’s language settings.
- Create an I18nProvider
component wrapping your App
component.
I18nProvider component need 2 values: messages and locale.
messages={messages} : defined as dictionary files, including key and value extracted from json files.
locale={locale} : defined as the current language (en-US, ja)
Messages can not be changed, if you wanna change them, you can use function selectLanguage
which is set into the component I18n
, then you will need Context
to the sub component can use it. And finally, we can see
value = {{locale, selectLanguage}}
means the value of Context.
- The app.js
file should:
Use the function handle like we used to do with React. Then, using Select of MUI to make the easier options.
- Syntax intl.formatMessage
and how to use
If you follow the standard documentation, you will see they add the following content to the files accordingly by using id like this:
But I suppose that the id will be caused trouble when you try to name it without duplicates. So I decide to keep keep the content of the sentence as an id like this:
- Don't forget to add the component I18n
into index.js
Okay let's see the website:
3. Summary
- Streamlined internationalization process for React projects.
- Intuitive API and comprehensive documentation for ease of use.
- Enhanced user experience and global reach through language preference detection and intuitive language selection interfaces.