How to Internationalize a React App – Step-by-Step Guide
Internationalization (i18n) is important for making your React app accessible to a global audience. In this step-by-step guide, we will show you how to internationalize a React app using i18n.
Step 1: Set Up i18n Library
The first step in internationalizing your React app is to set up an i18n library. There are several options available, but one popular choice is the react-i18next library. Install it using npm:
npm install i18next react-i18next
Step 2: Create Translation Files
Once the i18n library is set up, create translation files for each language you want to support. These files should contain key-value pairs for each string in your app that needs to be translated. For example, create en.json and es.json files for English and Spanish translations:
{
"welcome": "Welcome to our app",
"about": "About Us",
"contact": "Contact Us"
// Add more key-value pairs for other strings in your app
}
Step 3: Configure i18n Library
Next, configure the i18n library to use the translation files you created. This can be done in your app’s main entry point, such as index.js:
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
i18n.use(initReactI18next).init({
resources: {
en: {
translations: require('./locales/en.json')
},
es: {
translations: require('./locales/es.json')
}
},
lng: 'en',
fallbackLng: 'en',
interpolation: {
escapeValue: false
}
});
Step 4: Add Language Selector
Add a language selector to allow users to switch between supported languages. This can be a dropdown menu or a set of flag icons, for example.
Step 5: Translate Your App
Finally, use the i18n library to translate the strings in your app. This can be done using the useTranslation hook provided by react-i18next, for example:
import { useTranslation } from 'react-i18next';
function App() {
const { t } = useTranslation();
return (
{t('welcome')}
{t('about')}
{t('contact')}
);
}
By following these steps, you can internationalize your React app and make it accessible to users around the world. Internationalization is a crucial part of a user-friendly and inclusive user interface, so be sure to consider it in your app development process.
Hey man, can i get the source code? thx for this video
Nice Tutorial. Make a tutorial for next js 13. It's also helpfull for all and me🙂.I am trying to do this in next js 13. If I done it, I will try to make a video on it.