Internationalization in React
Internationalization (i18n) is the process of making your application adaptable to different languages and regions without requiring code changes. In this tutorial, we will demonstrate how to implement internationalization in a React application using the react-i18next
library.
Installing react-i18next
First, you need to install the react-i18next
and i18next
packages:
npm install react-i18next i18next
Setting up i18n
Create a new folder called i18n
in your src
folder, and then create an index.js
file in the i18n
folder. Configure i18next
as follows:
// src/i18n/index.js
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
const resources = {
en: {
translation: {
welcome: 'Welcome to our application!',
changeLanguage: 'Change Language',
},
},
es: {
translation: {
welcome: '¡Bienvenido a nuestra aplicación!',
changeLanguage: 'Cambiar idioma',
},
},
};
i18n.use(initReactI18next).init({
resources,
lng: 'en',
keySeparator: false,
interpolation: {
escapeValue: false,
},
});
export default i18n;
Here, we define translations for two languages: English (en) and Spanish (es). You can add more languages and translations as needed.
Integrating i18n in your application
Next, import the i18n
configuration in your src/index.js
file:
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './i18n'; // Import i18n configuration
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
Using translations in your components
To use translations in your components, import the useTranslation
hook from react-i18next
:
// src/App.js
import React from 'react';
import { useTranslation } from 'react-i18next';
function App() {
const { t, i18n } = useTranslation();
const changeLanguage = language => {
i18n.changeLanguage(language);
};
return (
<div>
<h1>{t('welcome')}</h1>
<button onClick={() => changeLanguage('en')}>English</button>
<button onClick={() => changeLanguage('es')}>Español</button>
</div>
);
}
export default App;
In this example, we use the t
function to translate strings and the changeLanguage
function to switch between languages.
Conclusion
Now your React application is ready to support multiple languages, providing a better experience for users from different regions and language preferences.