This React multi-language component is to support the internationalization of a React application. As an example, this component showcases support for three languages: English, German, and Spanish, which you can extend or change for any languages.
This quick example achieves internationalization with inline JSON language configurations.
This tutorial has another React example that uses the popular JavaScript library i18next to support multi-language.
src/MultiLanguageComponent.js
import React, { useState } from 'react';
import './form.css';
import './style.css';
// MultiLanguageComponent: A React component for rendering a webpage with multi-language options.
const MultiLanguageComponent = () => {
const [language, setLanguage] = useState('en');
// Site content in English, German and Spanish languages
const text = {
heading: {
en: 'Helping you build websites',
es: 'Ayudándote a construir sitios web',
de: 'Wir helfen Ihnen beim Erstellen von Websites',
},
extraText: {
en: `
Do you want to build a modern, light-weight and responsive website? or wish to upgrade? contact support.
You can also order a free review report.
`,
es: `
¿Quiere crear un sitio web moderno, liviano y responsivo? ¿Tienes un deseo? Soporte de contacto.
También puede solicitar un informe previo a la revisión
`,
de: `
Möchten Sie eine moderne, schlanke und reaktionsfähige Website erstellen? Haben Sie einen Wunsch? Kontaktieren Sie Support.
Sie können auch einen Vorabbericht bestellen
`,
},
};
// JavaScript function to set currently selected language
const handleLanguageChange = (selectedLanguage) => {
setLanguage(selectedLanguage);
};
// Highlights active language
const linkStyle = {
fontWeight: 'bold',
};
// JSX for mounting the multi language component to the UI
return (
<div className="phppot-container">
<div className="textline">
<span>Select language : </span>
<a
href="#"
onClick={() => handleLanguageChange('en')}
style={language === 'en' ? linkStyle : {}}
>
en
</a>
<a
href="#"
onClick={() => handleLanguageChange('es')}
style={language === 'es' ? linkStyle : {}}
>
es
</a>
<a
href="#"
onClick={() => handleLanguageChange('de')}
style={language === 'de' ? linkStyle : {}}
>
de
</a>
</div>
<h1>{text.heading[language]}</h1>
<p>{text[language]}</p>
<div>
{text.extraText[language].split('\n').map((line, index) => (
<p key={index}>{line}</p>
))}
</div>
</div>
);
};
export default MultiLanguageComponent;
Import the MultiLanguageComponent
component into the main JS of the React app live below.
src/App.js
import './App.css';
// Importing the MultiLanguageComponent created for this App
import MultiLanguageComponent from "./MultiLanguageComponent";
// Main React App component
function App() {
return (
<div className="App">
<MultiLanguageComponent/>
</div>
);
}
export default App;
The useState('en')
initializes the default language. It is changed when selecting a language from the multi-language menu from the header.
The const text
has the language configurations of the three languages. This object array keeps the values using the two-character language codes (en, es, de).
The handleLanguageChange()
JavaScript event handler is called on choosing the language. It highlights the selected language and also changes the site content dynamically.
This method simplifies enabling multi-language support for a static, single-page website. It avoids the complexity of having a backend language module unnecessarily.
But, if you have a full-fledged application and want to add multi-language support, the backend should be modular.
The i18next
library is one of the best libraries that provides advanced features around website internationalization. It makes it easy to localize a page for a new language.
This library works with different front-end frameworks: React, Vue, and Angular. This example uses this library with a react component.
This library provides various features like variable interpolation to supply dynamic content to the translation content.
Install the i18next library integrated for React using npm install react-i18next
.
After importing the library the useTranslation and initReactI18next
functions can be used for language translation utility.
initReactI18next
– It initializes the i18next library for React component.useTranslation
– It is a hook to give the scope of accessing translation functions.The i18next-browser-languagedetector
is the JavaScript library to detect the users’ language using its LanguageDetector
hook. Run npm install i18next-browser-languagedetector
to use this library in this React multi-language app.
It is for configuring the site’s default language based on the user’s regional language. In a previous tutorial, we saw how to get the user IP address by the client region.
The translations
source is imported from translations.json
, which contains the translations for different languages.
src/MultiLanguageComponent.js
(Imports)
// Importing React and translation modules from the 'react-i18next' library
import React from 'react';
import { useTranslation, initReactI18next } from 'react-i18next';
// Importing i18next and its browser language detector
import i18n from 'i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import './form.css';
import './style.css';
// Importing translation resources from JSON
import translations from './translations.json';
The below code maps the imported library services to be used by the i18next library. The init()
function sets the fallback language and the JSON resource.
The fallback language is English, which will be set in case of an uncertain scenario. That means if anything is wrong with detecting or loading the resources of the detected language.
The MultiLanguageComponent
created in this example calls the changeLanguage()
on selecting a language. It sets the selected language to the changeLanguage()
to call the i18next
service about its instance.
Then, the library service sets the language code to be highlighted and selected among the language menu items.
This example uses a horizontal menu with three languages in the header view. It can also be changed to a React dropdown for effective screen real estate optimization.
src/MultiLanguageComponent.js
// Initializing i18next with language detector and React integration
i18n
.use(LanguageDetector)
.use(initReactI18next)
.init({
fallbackLng: 'en',
resources: translations,
});
const MultiLanguageComponent = () => {
// useTranslation hook to access translation functions of react-i18next
const { t, i18n } = useTranslation();
// Function to handle language menu 'on-click' event
const changeLanguage = (lng) => {
i18n.changeLanguage(lng);
};
return (
<div className="phppot-container">
<div className="textline">
<span>Select language:</span>
<a onClick={() => changeLanguage('en')} style={{ fontWeight: i18n.language === 'en' ? 'bold' : 'normal' }}>
en
</a>
<a onClick={() => changeLanguage('es')} style={{ fontWeight: i18n.language === 'es' ? 'bold' : 'normal' }}>
es
</a>
<a onClick={() => changeLanguage('de')} style={{ fontWeight: i18n.language === 'de' ? 'bold' : 'normal' }}>
de
</a>
</div>
<h1>{t('heading')}</h1>
<p>{t('text')}</p>
<div className="text">
<p>{t('Text')}</p>
</div>
</div>
);
};
export default MultiLanguageComponent;
Thus, we learnt React multi-language with or without library. Also, we have an introduction about the basic usage of the react-i18next library.
View demo Download