React localization/internationalization with i18n

Published on November 27, 2024

React localization/internationalization with i18n

React localization (l10n) is the process of adapting your application for a specific locale or market so that you can increase accessibility and market reach. This is built on top of React internationalization (i18n), which lets your application switch between multiple languages and enables localization by minimizing the future development work required to support additional languages.

This post explains how to implement React internationalization and React localization, enabling your application to support multiple languages and regional settings efficiently.

Localization vs. internationalization: What's the difference?

I18n is a process that prepares software for various languages. It typically involves setting up structure for translation files and user interface adjustments for different languages. In this article we will be using i18n for React internationalization.

L10n is a process which adapts your application for specific locales, taking into account cultural references, vocabulary, and formatting preferences. It involves designing an application to support these features without requiring major changes to the codebase. It is a set of technologies and architectural decisions which, if implemented early in the development cycle, can make it easier to tailor your app for new users when expanding your product to new marketplaces. Typically, your application will go through the internationalization process before moving on to localization.

In JavaScript, the Intl namespace provides common functionality for adapting your application to different languages. React i18next is a dedicated library that can be used to provide enhanced React internationalization and React localization.

Localization vs. internationalization: What's the difference?

What are the benefits of localizing your application?

React localization helps your product reach a global audience, going beyond mere translation and adapting your user interface (UI) to meet the cultural and linguistic needs of different regions. There are multiple benefits to localizing your project:

  • Open your application up to other markets: Adapting your content to meet the specific language or culture of a desired market can help you to compete and make your users feel welcome, leading to increased traffic or sales.

  • Formatting numbers and dates helps with clarity: Making sure numbers (using commas vs. periods) and dates (MM/DD/YYYY vs. DD/MM/YYYY) are formatted correctly can help to avoid confusion and improve the user experience.

  • Displaying currencies correctly: Using dots vs. commas for decimals, correct currency symbols, and handling significant figures correctly is ideal for localization. Making sure currencies are displayed correctly is important in any apps that handle financial data or have business use cases; badly formatted dates and currencies could cause confusion about events and requested refunds on customer purchases.

  • Search engine optimization (SEO): Optimizing localized content for search engines in different languages can have a positive impact on SEO, increasing visibility and attracting more users.

  • Cultural relevance: Adapting content to reflect local customs and cultural nuances helps your messaging resonate with your target audience. For example, your translations into each language can be carefully crafted and idiomatic, rather than using machine translation, which may result in clunky language that may not communicate the intended meaning.

  • Improve accessibility: Ensuring your users can interact with your app in a way that feels natural and intuitive by using familiar language and cultural references makes it more approachable for all users.

By investing in localization, you can create a more open and diverse application that resonates with your target audience, helping you to break into more markets and maintain a good user experience.

How React localization works

The first thing you will want to consider is how you will acquire translations for the data in your app. There are a few different options available to you: You can use AI and translate your app manually, and there are various translation APIs that allow you to connect your project and automate translations. But for the best results, you can hire a translation company or an individual who knows the nuances of the language.

Once you have your translations ready, assuming you're not using an automated API service, you will need to use an i18n library like React i18next to plug the translations into your code. If you're using a content management system (CMS), then you will likely use a mixture of plugins that offer multilingual and locale support.

When a user lands on your website, you can either offer a language switcher offering a selection of locales that your app has been translated into for the user to pick from, or utilize one of the various libraries that offer the ability to automatically detect the language of the user through the browser. It is best practice to use a mixture of both techniques.

Translation files

At the heart of your localization system, you will have translation files. They consist of JSON files where the content is segmented into strings that have unique IDs (translation keys), usually stored together in a centralized location within your application.

For example, you might have an English translation file that has a title key with the corresponding string value of "Welcome!"

And another translation file for Italian:

Namespaces

Namespaces in i18next allow you to group your translations into logical components that can simplify the management and loading of translations in complex applications. Using a namespace, the translations above could be grouped together for a dashboard component and other additional translations for a footer component, allowing you to load only the necessary parts of the translation files when needed.

Translation files: Inline vs. asynchronous

Inline translation files are stored within the project's file structure. This is okay for small projects where only a few translations are needed, but as apps scale and grow, the config file will become bloated and hard to maintain, slowing down the initial app load.

The solution is to organize and separate the translation files one per locale and then load them asynchronously when needed from the network which is a feature that comes built into Contentful. This is a modular approach and helps with maintainability by keeping everything organized. Performance is improved by not loading all translation data at once. Also, scalability is improved, because adding a new locale as the app grows is as easy as adding a new locale file.

You can implement asynchronous loading of translation files from the network by installing the official i18next HTTP API backend plugin.

Locale codes

Locale codes are standardized identifiers representing different languages and regional dialects; they use familiar language tags such as en for English or es for Spanish and add regions or countries with ISO alpha 2 codes such as US for the United States or GB for Great Britain. These codes are important, as they allow developers to handle language nuances, such as dialects. As a simple example, en-US and en-GB differ in spellings like "color" vs. "colour" or vocabulary like "garbage" vs. "rubbish."

Right-to-left languages

Many languages (such as Hebrew and Arabic) are read right to left and should be accommodated when localizing applications. Modern web browsers make it easier to support right to left (RTL) document flow, by managing most of the complex tasks involved. When working with React localization, you only need to perform minimal adjustments to your applications to fully support RTL: i18next can detect the directionality of a given locale via its i18n.dir() method.

React i18next: React internationalization how-to guide

React internationalization and React localization can be achieved with a few different libraries: React-i18next is the most popular, and react-intl and Lingui are other options. Let's go over a few code examples to show how to set it up and use it to solve some different problems.

Code examples of React localization

React i18next can be added to your project by running:

npm install react-i18next i18next --save

Basic translation with React i18next

As a basic example, create a configuration folder inside a utils folder or in the root of the application called i18n, add a translations folder that will contain the JSON translation files, and create an index.js file.

Please note the above initialization will need to be imported into the root of your application (example in vite.js):

You can import useTranslation into components to access translation keys and display translations:

How to detect language in React i18next

You can use the - i18next-browser-languagedetector from npm to automatically pick up the user's language from the browser and switch it in your application.

Using variables in React i18next

Standard translation keys work well for static strings and general messages; however, when you want to personalize messages, such as by including user-specific information with dynamic data, interpolation (that is, using variables in translations) becomes necessary.

In the translation files, use a {{variable}} syntax to pass dynamic values through.

It can then be used in components to pass dynamic values:

Switching languages in React

You can improve the user experience by providing functionality to manually select the preferred locale. You can add this with the built-in changeLanguage function:

This can now be imported into a component of your choice to display a dropdown for users to switch between different languages.

Pluralization in React localization

To work with plurals in React i18next, you need to define plural forms in the translation files and then pass the variable name count followed by the number:

You can use the t function from useTranslation in your component to pass the count variable to access plural strings:

Some languages, such as Arabic, have multiple plurals. In much the same way, you can just define the different values and let i18n logic handle pluralization:

Replacing the string values with your translated Arabic examples, you can now handle complex plurals in your components:

Setting a fallback language

If the translation is missing in the current language or translations in the user's preferred language cannot be displayed, rather than display an error, you can easily add a parameter to the initialization to display a fallback language:

How to format dates in React

The format of dates varies from country to country, and this issue can be addressed with interpolation in React i18next. Take,  for example, the difference in order between U.S. English (MM/dd/yyyy) and Italian (dd/MM/yyyy).

In your translation files, you can specify a date variable with the desired format:

You can then specify a format function for interpolation in the initialization (using a date formatter library such as Moment.js):

Now you can format dates when switching between languages with i18next:

return <p>{t('dateKey', { date: new Date() })}</p>;

Custom formatters for React internationalization/localization

In React localization, custom formatters are used to handle complex value formatting, such as formatting currency or converting units (converting a price to the correct currency format based on the user's locale). For instance, there are differences in formatting dates between different English-speaking countries such as en-GB and en-US.

By default, when i18next falls back to a language, it only uses the country code (en,it); it doesn’t take the region into account. This is where a custom formatter would come in handy to distinguish between regions.

You can create a custom function for formatting dates and then override the default behavior of i18next by creating a formatter file with the following code:

Now add the datetime format function to i18next to override the default behavior:

You can now use this custom function in your translation files like so:

Now, when the browser falls back to English, it uses en-GB instead of en-US. You can check out the i18next formatting guide for more info about date formatting, including relative dates.

The above covers some of the most popular needs of localization. You can read through the documentation to gain a deeper understanding.

React localization for mobile apps

React native localization differs slightly from normal React localization. Unlike with web apps, mobile localization relies on device-specific language settings and requires bundling language resources differently to work offline.

The Expo framework for React native offers significant advantages for React native localization with its library expo-localization. This integrates directly with the device's locale settings, allowing you to detect languages easily. This library is simple to set up and easy to maintain, making it a popular choice when it comes to multilingual mobile apps.

Best practices for React localization

Here is a list of best practices for implementing localization in your applications:

  • Make sure you are using the right region-specific language (French vs. Canadian French, British English vs. U.S. English) by setting the locale.

  • Provide users with the option to manually switch languages in case the wrong one is set by default (for example, if they're on vacation in another country).

  • Make sure that UI limits the use of sayings, cultural phrases, and idioms that don't translate well.

  • Test the UI in different languages, because some languages may use much larger words that may break the page layout.

  • Specify a fallback language in your i18n configuration to prevent the app from breaking or displaying untranslated strings when a translation is missing for the current locale.

  • Avoid hardcoding text in your components.

  • Use meaningful translation keys.

  • Consider multilingual SEO when localizing your apps.

Composable content tailors your omnichannel campaigns based on region and language

Contentful lets you write your content in multiple languages and store it in a composable content platform that can be accessed by React localization tools, simplifying editing for non-developers and translators. Your creators can create content in multiple languages, and front ends can automatically load the content based on the user's detected language, region, or settings.

Contentful even allows you to apply field level localization on your content so you can build translations in as you are creating content. Improving React localization can make your apps seem like they were made locally, increasing user satisfaction and customer retention.

Subscribe for updates

Build better digital experiences with Contentful updates direct to your inbox.

Related articles

How to future-proof your content platform with a composable approach that’s less painful than traditional replatforming projects – and more cost effective.
Guides

CMS replatforming made easy with Contentful

September 26, 2023

Moving from a content management system (CMS) to a new platform? The Contentful Learning Center offers a complimentary guide about migrating to Contentful.
Guides

Migrating to Contentful: Plan and implement with confidence

May 2, 2023

How to use Redux to manage application state and data-fetching logic in a React project, and how to apply these techniques to data coming from Contentful.
Guides

Redux tutorial with Contentful

April 7, 2023

Contentful Logo 2.5 Dark

Ready to start building?

Put everything you learned into action. Create and publish your content with Contentful — no credit card required.

Get started