How to implement localization in your React App
How to implement localization using react-intl
In this tutorial I am gonna guide you how you can introduce localization in your react app. Before diving into detail, let me tell you what is localization. Localizaion of your app is nothing but providing your app users’ a privilege to read app’s text in a language of their choice translated by you. Read more here
The codebase for this tutorial is https://github.com/debabrata100/react-localization
After the end of tutorial we should be able to achieve this
We will finish this in 4 steps:
- Project setup and installation from scratch
- Add header, footer and language dropdown
- Define messages in different locales and initialize react-intl
- Render correct text for locale selected
NOTE: This tutorial is based on create-react-app
Install create-react-app on your machine$ npm i -g create-react-app
1. Project setup and installation
Initialize your react boilerplate
$ create-react-app react-localization
Add react-intl(2.8.0) to your project.
$ yarn add react-intl@2.8.0
Start your project $ yarn start
2. Add header, footer and language change dropdown
Let’s add some text in Header and Footer section where we will format our text to different locales as well as add some style to our application. We will also add a dropdown to select different locales and save the selected locale in react component state as well as in localStorage.
You can add header and footer text as below
<div className="App">
<h1>Localization in Create React App</h1>
<footer>Love you 3000</footer>
</div>
Now let’s add the dropdown to select a locale. For now let’s add only one locale as English
<select>
<option value="en">English</option>
</select>
Now let’s add some more languages in a list and render the list. We will subscribe to the event on change of dropdown as shown below.
const defaultLocale = localStorage['locale'] ? localStorage['locale'] : 'en'; // English is default locale if none //is setconst localeList = [
{ name: 'English', code: 'en', lang: 'English' },
{ name: '中文', code: 'zh', lang: 'Chinese' },
{ name: 'русский', code: 'ru', lang: 'Russian' },
{ name: 'Française', code: 'fr', lang: 'French' }
];const [currentLocale, setCurrentLocale] = useState(defaultLocale);const onChangeLanguage = (e) => {
const selectedLocale = e.target.value;
setCurrentLocale(selectedLocale);
localStorage.setItem('locale',selectedLocale)
}...<select onChange={onChangeLanguage} defaultValue={currentLocale}>
{
localeList.map((locale,index)=>(
<option key={index} value={locale.code}>{locale.name}</option>
))
}
</select>
I have used react hooks. If you are not familiar with hooks, you can create a class component. I have used localStorage here to store the locale so that even if we refresh the page, we will set our locale value as last selected. We have assigned localStorage value to defaultLocale variable.
Add some styles to App.css as below
.App {
text-align: center;
}
footer{
margin-top: 24px;
display: flex;
flex-direction: column;
justify-content: center;
}
Post these changes our component should look as below
At this stage after running the app $ yarn start
you should be able to see below screen
3. Define messages in different locales and initialize react-intl
In this section, we will define header and footer text in different locales to a messages variable and initialize react-intl library to manipulate different locale text by selecting a specific locale value from the dropdown we have already created.
Let’s define 4 different locales for our text as below.
const messages={en: {
'dashboard.header': `Localization in Create React App`,
'dashboard.footer': 'Love you 3000'
},zh: { 'dashboard.header': `Create React App中的本地化`,
'dashboard.footer': `爱你3000`
},ru: { 'dashboard.header': `Локализация в приложении Создать React`,
'dashboard.footer': `Люблю тебя 3000`
},fr: { 'dashboard.header': `Localisation dans l'application Create React`,
'dashboard.footer': `Je t'aime 3000`
}}
Now let’s initialize react-intl. To do this we will follow these steps
- import IntlProvider wrapper from react-intl
- import pre-defined locales from react-intl
- import addLocaleData method from react-intl
- register locales to react-intl by calling addLocaleData method
- wrap our entire component with IntlProvider to pass locale value and defined messages to react-intl
#step-1
import { IntlProvider } from 'react-intl';#step-2
const en = require('react-intl/locale-data/en');
const zh = require('react-intl/locale-data/zh');
const ru = require('react-intl/locale-data/ru');
const fr = require('react-intl/locale-data/fr');#step-3
const addLocaleData = require('react-intl').addLocaleData;#step-4
addLocaleData(en);
addLocaleData(zh);
addLocaleData(ru);
addLocaleData(fr);
...
<IntlProvider locale={currentLocale} messages={messages[currentLocale]}>
<App>
...
</App></IntlProvider>
4. Render text for locale selected
To use our saved texts of different languages, we will follow these steps
- import FormattedMessage component
- pass messages variable to IntlProvider component as props to detect specific locale text
- render FormattedMessage component and format our locale specific text
#step-1
import { IntlProvider, FormattedMessage } from 'react-intl';#step-2
<IntlProvider locale={currentLocale} messages={messages[currentLocale]}>#step-3##header text
<FormattedMessage id="dashboard.header" defaultMessage="Localization in Create React App"/>## footer text
<FormattedMessage id="dashboard.footer" defaultMessage="Love you 3000"/>
We have passed messages as messages[currentLocale]. Here currentLocale will determine which locale message we are going to render. e.g messages[‘en’]
We have passed 2 props id and defaultMessage to FormattedMessage component. id is to detect which part of (header/footer) text to be rendered. And defaultMessage will render text in case no message is defined for that id value.
At this stage your final App.js file should look as below.
Copy the above code to your App.js file and try running our app. You should be able to see below screen.
Now we are done with a successful implementation of localization for a react project. I hope you are not confused at any point. You can even format numbers, datetime and pluralize words. To learn more visit react-intl docs.
Here I have a challenge for you. Set up your project in such a way that by default it should render correct locale for the part of the world where your application is accessed. I will be eager to know which approach you have followed in the comment section.
What’s next ?
We can organize our code and project folder structure in a better way. You can follow the repository I have made for you :)
To find this tutorial version of the app
$ git checkout b55dd17
Thanks for reading the article. I am there to check your valuable responses :)