[React] 다국어 처리 react-i18next

Lemon·2022년 11월 7일
4

React

목록 보기
16/21
post-thumbnail

react-i18next를 사용해서 언어를 전환하는 버튼을 만들 것입니다

🔗 참고 링크
Best React Localization - Internationalize with i18next (a react-i18next guide)
아래의 내용은 참고 링크(react-i18next 공식 문서)를 정리한 내용입니다.


react-i18next란

자바스크립트 국제화 프레임워크


사전 조건

  • Node.js 및 npm 설치 확인
  • HTML, JavaScript 및 기본 React.js에 대한 경험 필요

설치

npm install i18next react-i18next i18next-browser-languagedetector

사용 방법

CRA로 만든 react 프로젝트 기준

1. 📜index.js 에 i18n import

import React from 'react';
import { createRoot } from 'react-dom/client';
import './index.css';
import App from './App';

import './i18n'; // import만 해두면 된다.

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

2. 📜 i18n.js 생성

import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import LanguaeDetector from "i18next-browser-languagedetector";

i18n
  .use(LanguaeDetector) // 사용자 언어 탐지
  .use(initReactI18next) // i18n 객체를 react-18next에 전달
  .init({
    // for all options read: https://www.i18next.com/overview/configuration-options
    debug: true,
    fallbackLng: "en",
    interpolation: {
      escapeValue: false,
    },
    resources: {
      en: {
        translation: { // 번역본 쓸 공간
          description: {
            part1: "Edit <1>src/App.js</1> and save to reload.",
            part2: "Learn React",
          },
          counter_one: "Changed language just once",
          counter_other: "Changed language already {{count}} times",
        },
      },
      de: {
        translation: { // 번역본 쓸 공간
					description: {
            part1: "Ändere <1>src/App.js</1> und speichere um neu zu laden.",
            part2: "Lerne React",
          },
          counter_one: "Die Sprache wurde erst ein mal gewechselt",
          counter_other: "Die Sprache wurde {{count}} mal gewechselt",
        },
      },
      ko: {
        translation: { // 번역본 쓸 공간
          description: {
            part1: "src/App.js를 편집하고 저장하여 다시 로드합니다.",
            part2: "React 배우러가기",
          },
          counter_one: "언어를 한번 바꾸었습니다.",
          counter_other: "언어를 {{count}}번 바꾸었습니다.",
        },
      },
    },
  });

export default i18n;

3. 📜 App.js

언어 전환기 만들기

import { useTranslation, Trans } from 'react-i18next'; // 1. react-i18next import 

const lngs = { // 2. 언어 구분을 위한 lng 객체 생성
  en: { nativeName: 'English' },
  de: { nativeName: 'Deutsch' },
	ko: { nativeName: "Korean" },
};

function App() {
  const { t, i18n } = useTranslation(); // 3. useTranslation hook 선언 

  return (
    <div className="App">
      <header className="App-header">
	      <div>
          {Object.keys(lngs).map((lng) => (
            <button key={lng} style={{ fontWeight: i18n.resolvedLanguage === lng ? 'bold' : 'normal' }} type="submit" onClick={() => i18n.changeLanguage(lng)}> // 4. 버튼 클릭 시 해당 언어로 전환시킨다.
              {lngs[lng].nativeName}
            </button>
          ))}
        </div>
        <p>
          <Trans i18nKey="description.part1"> // 5. 현재 감지된 언어의 description.part1을 조회한다. 
            Edit <code>src/App.js</code> and save to reload.
          </Trans>
        </p>
        <p>{t('description.part2')}</p> // 5. 현재 감지된 언어의 description.part2를 조회한다.
      </header>
    </div>
  );
}

export default App;

추가 설명

  • i18next.resolvedLanguage : 현재 확인된 언어로 설정된다.

  • i18next.changeLanguage(lng, callback) : 언어를 변경한다. 번역이 로드되거나 로드하는 동안 오류가 발생하는 즉시 콜백이 호출된다.

  • useTranslation hook

import React from 'react';
import { useTranslation } from 'react-i18next';

export function MyComponent() {
  const { t, i18n } = useTranslation();
  // or const [t, i18n] = useTranslation();

  return <p>{t('my translated text')}</p>
}

대부분의 경우 콘텐츠를 번역하는 데 t 함수만 필요하지만 언어를 변경하기 위해 i18n 인스턴스도 얻을 수 있다.

i18n.changeLanguage('en-US');
profile
프론트엔드 개발자 가보자고~!!

2개의 댓글

comment-user-thumbnail
2022년 11월 10일

초반에 i19next는 오타인거 같아서 남겨요!

1개의 답글