React is a popular JavaScript library for building user interfaces, and internationalization (i18n) is the process of adapting software to support multiple languages. In this blog, we’ll look at how to use React to add i18n support to your application.
To start, you’ll need to install the react-i18next
library, which provides the components and functions you’ll need to support i18n in your React app. You can install it using npm or yarn:
npm install react-i18next
or
yarn add react-i18next
Once you’ve installed the library, you’ll need to configure it by creating a i18n
instance and passing it to the I18nextProvider
component, which should wrap your entire app. You’ll also need to create a file for each language you want to support, which will contain the translated strings for your app.
Here’s an example of how to configure react-i18next
and use it to translate a simple string in a React component:
import { I18nextProvider, useTranslation } from 'react-i18next'; import i18n from 'i18next'; // Initialize the i18n instance i18n.init({ lng: 'en', resources: { en: { translation: { "hello": "Hello, World!" } }, fr: { translation: { "hello": "Bonjour, le monde!" } } } }); function App() { const { t } = useTranslation(); return ( <div> {t('hello')} </div> ); } // Wrap the app with the I18nextProvider component ReactDOM.render( <I18nextProvider i18n={i18n}> <App /> </I18nextProvider>, document.getElementById('root') );
In the example above, the t
function is used to translate the string “hello” into the current language. By default, the current language is set to English (en
), but you can use the i18n.changeLanguage
function to switch to a different language at runtime.
Here’s an example of how to switch the language in response to a user action:
import { useTranslation } from 'react-i18next'; function LanguageSwitcher() { const { i18n } = useTranslation(); function handleLanguageChange(event) { i18n.changeLanguage(event.target.value); } return ( <div> <select onChange={handleLanguageChange}> <option value="en">English</option> <option value="fr">French</option> </select> </div> ); }
In the example above, the language is changed when the user selects a different option in the dropdown menu.
Thanks for reading you can ask doubts in comment section.