DEV Community

Cover image for Build a multi-language website using React in 3 minutes
quocbahuynh
quocbahuynh

Posted on • Updated on

Build a multi-language website using React in 3 minutes

If you are finding a way to build a website that uses multiple languages. This place is for you.

The hero of this solution is React-I18next. It's a react library that is used for translating languages. You can install the library by the command line below:



npm install i18next react-i18next@latest


Enter fullscreen mode Exit fullscreen mode

To start off, we need to configure the library:

1. Create an initiation i8next file. I will name it i18n.js:



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

i18n
  .use(initReactI18next)
  .init({
    debug: true,
    fallbackLng: 'en',
    interpolation: {
      escapeValue: false, // not needed for react as it escapes by default
    },
    // language resources
    resources: {
      en: {
        translation: {
         welcome: "Welcome to React"
        }
      },
      vn: {
        translation: {
         welcome: "Chào mừng đến với bình nguyên vô tận"
        }
      },
    }
  });

export default i18n;


Enter fullscreen mode Exit fullscreen mode

Next, import the file into index.js



//pla pla
import './i18n'

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);



Enter fullscreen mode Exit fullscreen mode

Let's notice the resource property where you can push more corresponding language. In a real-world project, this resource can come from a database (we will discuss in another article) but to keep the demonstration simply, I would like to translate English into Vietnamese and use an object directly. The default language is English.

2. Play with the library.

The idea is that the user will click on the button to translate languages on the website. Let's open App.js

To display and switch between two languages, the library provides useTranslation(). It's a react-18next built-in that exposes some functions as below:



import { useTranslation } from 'react-i18next';

export default function App() {

  const { t, i18n } = useTranslation();

  return (
    <div>
      <h1>{t('welcome')}</h1>
    </div>
  );
}
export default App;


Enter fullscreen mode Exit fullscreen mode

We use t to get content by the key object in the resource object where we have configured it. The default language is English so it displays Welcome to React.



import { useTranslation } from "react-i18next";

const lngs = [
  { code: "en", native: "English" },
  { code: "vn", native: "Vietnamese" },
];

export default function App() {
  const { t, i18n } = useTranslation();

  const handleTrans = (code) => {
    i18n.changeLanguage(code);
  };

  return (
    <div style={{padding: '50px'}}>
      <h1>{t("welcome")}</h1>

      {lngs.map((lng, i) => {
        const { code, native } = lng;
        return <button onClick={() => handleTrans(code)}>{native}</button>;
      })}

    </div>
  );
}


Enter fullscreen mode Exit fullscreen mode

Next, the i8next instance contains changeLanguage function which is used for changing language by country code. It takes a parameter as a country code (en and vn).

3. Result

result

Finally, I hope it will be helpful to you. If you want me to use it with the database, just comment below. Really recommend you visit their document to learn the way to scale a huge project.
Buy Me A Coffee

Top comments (24)

Collapse
 
projectlac profile image
Tim Dang • Edited

Bình nguyên vô tận mới chịu =))

Collapse
 
nttminh profile image
Minh Nguyen

Đọc phát nhìn lại tác giả mới biết VN =))

Collapse
 
quocbahuynh profile image
quocbahuynh

đồng hương trên đất khách quê ng 🤣🤣

Collapse
 
tus profile image
Tu

đọc lướt qua thấy hết hồn =)))

Collapse
 
quocbahuynh profile image
quocbahuynh

dịch sát nghĩa lắm rồi :))

Collapse
 
drfcozapata profile image
Francisco Zapata

Great! Thanks.
Greetings from Venezuela

Collapse
 
alberto8899 profile image
Alberto (알베르토)

Great article, thanks !

Collapse
 
lucasferreiralimax profile image
Lucas

Very nice article, i have a article with implementation with lazyLoading locales too react i18n in this link - dev.to/lucasferreiralimax/how-impl...

Collapse
 
quocbahuynh profile image
quocbahuynh

very helpfullll

Collapse
 
payam101020 profile image
Payam101020

ty

Collapse
 
caioragazzi profile image
Caio Ragazzi

Thanks for sharing!!!

That is really useful!

Collapse
 
pedroluizap profile image
Pedro Luiz A. Silva

This is very useful, so I can serve 2 audiences in my projects.
I usually do all the code in English but I live in Brazil.

Collapse
 
arsalannury profile image
ArsalanNury

it was really **helpful **thank you

Collapse
 
quocbahuynh profile image
quocbahuynh

keep supporting me in next articles <3

Collapse
 
taitrinh153 profile image
taitrinh153

Nai sừ =))))

Collapse
 
Sloan, the sloth mascot
Comment deleted