Bài viết này chúng ta cùng tìm hiểu cách cài đặt i18n trên react. I18n là một thư viện được sử dụng để thiết kế các website đa ngôn ngữ.

Cách cài đặt

Đầu tiên chúng ta khởi tạo dự án

  • npx create-react-app i18n-app

Cài đặt thư viện

  • npm install i18next react-i18next

Cấu hình cho i18n

Bên dưới thư mục src chúng ta tạo thêm một thư mục locates. Sau đó tiếp tục tạo hai thư mục con là vi, en.

  • file src/locates/vi/common.json
{
  "hello": "Xin chào"
}
  • file src/locates/en/common.json
{
  "hello": "Hello"
}
  • file src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import i18n from 'i18next';
import { I18nextProvider } from 'react-i18next';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import common_vi from './locates/vi/common.json';
import common_en from './locates/en/common.json';

i18n.init({
  interpolation: { escapeValue: false },
  lng: 'en',
  resources: {
    vi: {
      common: common_vi,
    },
    en: {
      common: common_en,
    },
  },
  defaultNS: 'common',
});

ReactDOM.render(
  <React.StrictMode>
    <I18nextProvider i18n={i18n}>
      <App />
    </I18nextProvider>
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
  • lng: Ngôn ngữ sử dụng để translate, ở đây mình đang để là en.

  • resource: Dùng để khai báo các tệp translate cho các ngôn ngữ. Như trên mình đang khai báo khai ngôn ngữ là envi. Bên trong mỗi ngôn ngữ mình khai báo một namespace là common.

  • defaultNS: Giá trị mặc định của namespace.

  • file src/App.js

import { useTranslation } from 'react-i18next';
import './App.css';

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

  const changeLanguage = (lang) => {
    i18n.changeLanguage(lang);
  };

  return (
    <div>
      <h1>{t('hello')}</h1>
      <button onClick={() => changeLanguage('en')}>En</button>
      <button onClick={() => changeLanguage('vi')}>Vi</button>
    </div>
  );
}

export default App;
  • useTranslation: Là hook được cung cấp bởi thư viện react-i18next. Nếu bạn không chỉ định namespace thì giá trị mặc định sẽ là defaultNS ở trên.
  • t: function dùng để translate.

Kết luận

Các bạn có thể tham khảo repository tại đây Github.

Tài liệu: