First of all, we need to install i18n into the React project, we do this by using the next command in VS Code:
npm install i18next react-i18next i18next-browser-languagedetector
first_tutorial.crearArchivo
import i18n from 'i18next'; import { initReactI18next } from 'react-i18next'; i18n .use(initReactI18next) // passes i18n down to react-i18next .init({ resources: { en: { translation: { conocer:{ titulo:"Knowledge", } }, }, es: { translation: { conocer:{ titulo:"Conocimientos", } }, }, // Add more languages and translations here }, lng: 'en', // Set the default language fallbackLng: 'en', // Fallback language interpolation: { escapeValue: false // React already escapes by default } }); export default i18n;
In the 'main.tsx' (or 'main.js') file, we'll also need to import:
import "./i18n";
Now, let's use it in an example:
import { useEffect } from "react"; /*Import from i18n */ import { useTranslation } from "react-i18next"; export const Example = () => { /*First, set variables*/ const { t, i18n } = useTranslation(); /*Detect the browser language to adapt to the user's language */ useEffect(() => { const lng = navigator.language; i18n.changeLanguage(lng); }, []); return ( <div> /*Use the t variable and choose the i18n text location*/ <h1>{t("conocer.titulo")}</h1> </div> ); };
Finally, we can test with the browser switching between English or Spanish with this example, we can also add more languages following the ISO language code into the i18n file.