How to dynamically add language to URL in React using i18next?

Viewed 125

I need to add language to url i.e. this is how the URL looks now http://localhost:3000/, http://localhost:3000/news, but it needs to be like this http://localhost:3000/en, http://localhost:3000/en/news.

At the same time, when someone sends a link to this site, the language must be taken from the link. Here is my code. Languages work, change on click.

import i18n from 'i18next'
import HttpApi from 'i18next-http-backend'
import LanguageDetector from 'i18next-browser-languagedetector'
import { initReactI18next } from 'react-i18next'

i18n
    .use(LanguageDetector)
    .use(initReactI18next)
    .use(HttpApi)
    .init({
        supportedLngs: ['ru', 'en', 'kk'],
        fallbackLng: "en",
        detection: {
            order: ["cookie", "localStorage", "htmlTag", "path", "subdomain"],
            caches: ["cookie"],
        },
        interpolation: {
            escapeValue: false
        }
    });

  export default i18n;

But how to add to URL automatically? Are there ready-made solutions for this?

1 Answers

it is possible to get the parameters from the URL with the help of useParams() hook available in react-routerv5.

While defining the url, you need to add a param value like this: <Route path="/:lang/news" component={News} /> where :lang is the value that you will receive from the URL.

Say someone enters yourapp.com/en/news, here parameter lang will be loaded with the value en. So, now to extract this value, you can use import { useParams } from "react-router-dom"; and then inside the function component (as hooks work inside functional components only): const { lang } = useParams(); where lang is your parameter.
After this, you could use i18n to translate as per the received language.

Related