Home > OS >  How to use translation by reference in i18n react?
How to use translation by reference in i18n react?

Time:12-04

The React site has two languages ​​(en, ru). From different sources, we need to send to a different translation. Now there is an initial en, it can be switched by the button to ru.

Is it possible to make it so that a different translation opens like this: https://sitename.com?en or https://sitename.com/en to English translation?

CodePudding user response:

To use translation by reference in i18n React, you will first need to define a translation object that contains the different translations for each language. For example:

const translations = {
  en: {
    title: "My Title",
    description: "My description",
  },
  ru: {
    title: "Моя название",
    description: "Мое описание",
  },
};

Then, you can use the useTranslation hook from the react-i18next library to access the current translation object and use it in your components. For example:

import { useTranslation } from "react-i18next";

function MyComponent() {
  const { t } = useTranslation();

  return (
    <div>
      <h1>{t("title")}</h1>
      <p>{t("description")}</p>
    </div>
  );
}

To switch between languages, you can use the i18n.changeLanguage() method, passing in the desired language code as the argument. For example:

import { useTranslation, withTranslation } from "react-i18next";

function MyComponent({ i18n }) {
  const { t } = useTranslation();

  function handleLanguageSwitch() {
    i18n.changeLanguage("ru");
  }

  return (
    <div>
      <h1>{t("title")}</h1>
      <p>{t("description")}</p>
      <button onClick={handleLanguageSwitch}>Switch to Russian</button>
    </div>
  );
}

export default withTranslation()(MyComponent); You can also use the useTranslation hook to pass the current language code to your components, which can be used to conditionally render different elements based on the language. For example:

import { useTranslation } from "react-i18next";

function MyComponent() {
  const { t, i18n } = useTranslation();

  return (
    <div>
      {i18n.language === "en" && (
        <h1>

CodePudding user response:

To use translation by reference in i18n react, you can use the react-i18next library. Here are the steps to follow:

Install the react-i18next library by running the following command in the terminal:

npm install react-i18next

Create a JSON file for each language that you want to support. For example, if you want to support English and Russian, you can create two JSON files named "en.json" and "ru.json" respectively.

In the "en.json" file, define the translations for English. For example:

{
  "hello": "Hello"
}

In the "ru.json" file, define the translations for Russian. For example:

{
  "hello": "Привет"
}

In the root component of your app, import the i18n instance from the react-i18next library and initialize it with the languages and the translation files. For example:

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

i18n
  .use(initReactI18next)
  .init({
    lng: 'en',
    resources: {
      en: {
        translation: require('./en.json')
      },
      ru: {
        translation: require('./ru.json')
      }
    }
  });

Use the useTranslation hook provided by the react-i18next library in your components to access the translations. For example:

import { useTranslation } from 'react-i18next';

function MyComponent() {
  const { t } = useTranslation();
  return (
    <p>{t('hello')}</p>
  );
}

To switch between languages, use the i18n.changeLanguage() method. For example:

import i18n from 'i18next';

function changeLanguage(language) {
  i18n.changeLanguage(language);
}

To use the translation by reference in the URL, you can create a custom route in your app that accepts the language code as a parameter. For example:

<Router>
  <Switch>
    <Route path="/:language" component={App} />
  </Switch>
</Router>

In the App component, you can use the language parameter from the URL to switch the language using the changeLanguage() method. For example:

import { useLocation } from 'react-router-dom';
import i18n from 'i18next';

function App() {
  const { language } = useLocation().params;
  i18n.changeLanguage(language);
  // ...
}

Now, when you visit https://sitename.com/en, it will automatically switch to the English translation, and when you visit https://sitename.com/ru, it will switch to the Russian translation.

CodePudding user response:

To implement this, you can use the window.location.search property in JavaScript to get the query string from the current URL. You can then parse the query string to extract the language code and use that to determine which language to use for the translations.

Here is an example of how you can implement this:

import { useState, useEffect } from 'react';

function App() {
  // Get the language code from the query string in the URL
  const queryString = window.location.search;
  const urlParams = new URLSearchParams(queryString);
  const languageCode = urlParams.get('lang') || 'en'; // default to 'en' if no lang is specified in the query string

  // Use the language code to determine which language to use for the translations
  const [language, setLanguage] = useState(languageCode);

  // Listen for changes to the query string in the URL and update the language code
  // accordingly
  useEffect(() => {
    function handlePopState(event) {
      const queryString = window.location.search;
      const urlParams = new URLSearchParams(queryString);
      const languageCode = urlParams.get('lang') || 'en'; // default to 'en' if no lang is specified in the query string

      setLanguage(languageCode);
    }

    window.addEventListener('popstate', handlePopState);

    return () => {
      window.removeEventListener('popstate', handlePopState);
    };
  }, []);

  // Use the language code to render the correct translations
  return (
    <div>
      {language === 'en' && <p>Hello, world!</p>}
      {language === 'ru' && <p>Привет, мир!</p>}
    </div>
  );
}

This code listens for changes to the query string in the URL and updates the language code accordingly. It then uses the language code to determine which language to use for the translations.

You can then use the language code to switch between different languages on your site. For example, you can create a language selector component that allows the user to switch between languages by clicking on a language code. This language selector component can then update the query string in the URL to reflect the selected language, which will cause the language code to be updated and the translations to be re-rendered.

Here is an example of how you can implement a language selector component:

function LanguageSelector() {
  const [language, setLanguage] = useState('en');

  function handleLanguageChange(event) {
    const languageCode = event.target.value;

    // Update the query string in the URL to reflect the selected language
    const searchParams = new URLSearchParams();
    search
  • Related