Open In App

How to handle internationalization with Hooks in React ?

Handling internationalization (i18n) involves using the state to manage the current language and updating the UI based on the selected language. This typically includes creating language files or dictionaries for each supported language and dynamically rendering the content based on the selected language in your components.

Step to Handling Internationalization with Hooks:

npm install i18next react-i18next

Example: Below is an example of handling internationalization with Hooks.






// App.js
import React from 'react';
import LanguageSwitcher
    from './components/LanguageSwticher';
import ExampleComponent
    from './components/Greeting';
import "../src/components/i18n"
 
const App = () => {
    return (
        <div>
            <LanguageSwitcher />
            <ExampleComponent />
        </div>
    );
};
 
export default App;




// i18n.js
import i18n from 'i18next';
import {
    initReactI18next
} from 'react-i18next';
 
i18n
    .use(initReactI18next)
    .init({
        resources: {
            en: {
                translation: {
                    greeting: 'Hello!',
 
                },
            },
            fr: {
                translation: {
                    greeting: 'Bonjour!',
                },
            },
        },
        lng: 'en',
        fallbackLng: 'en',
        interpolation: {
            escapeValue: false,
        },
    });
 
export default i18n;




// useLanguage.js
import {
    useState
} from 'react';
import i18n from './i18n';
 
const useLanguage = () => {
    const [currentLanguage, setCurrentLanguage] =
        useState(i18n.language);
 
    const changeLanguage = (language) => {
        i18n.changeLanguage(language);
        setCurrentLanguage(language);
    };
 
    return { currentLanguage, changeLanguage };
};
 
export default useLanguage;




// LanguageSwitcher.js
import React from 'react';
import useLanguage from './useLanguage';
 
const LanguageSwitcher = () => {
    const { currentLanguage, changeLanguage } = useLanguage();
 
    return (
        <div>
            <p>Current Language: {currentLanguage}</p>
            <button onClick={() =>
                changeLanguage('en')}>
                Switch to English
            </button>
            <button onClick={() =>
                changeLanguage('fr')}>
                Switch to French
            </button>
        </div>
    );
};
 
export default LanguageSwitcher;




/* LanguageSwitcher.css */
.language-switcher-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 8px;
    margin-bottom: 20px;
}
 
button {
    margin-top: 10px;
    padding: 8px 16px;
    font-size: 14px;
    cursor: pointer;
}
 
button:hover {
    background-color: #f0f0f0;
}

Step to run the App:

npm start

Output:



Output


Article Tags :