231101 개발일지 TIL - react-i18next 다국어 번역

The Web On Everything·2023년 10월 31일
0

개발일지

목록 보기
175/269

react-i18next 다국어 번역

React 프로젝트에서 국제화(i18n)를 쉽게 처리할 수 있게 도와주는 라이브러리
다양한 언어로의 번역을 지원하며, 동적으로 언어를 변경하는 것도 가능

1. 설치

// npm 
npm install react-i18next i18next

// yarn 
yarn add react-i18next i18next

react-i18next와 i18next를 설치

2. i18n.js 파일 설정

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

i18n
  .use(initReactI18next) // react-i18next를 i18next에 연결
  .init({
    resources: {
      en: {
        translations: { 
          "Welcome to React": "Welcome to React"
        }
      },
      kr: {
        translations: { 
          "Welcome to React": "React에 오신 것을 환영합니다"
        }
      }
    },
    lng: "en", // 기본 언어를 영어로 설정
    fallbackLng: "en", // 번역할 수 없는 문자열이 있을 경우 사용할 기본 언어 설정
    debug: true,

    ns: ["translations"],
    defaultNS: "translations",

    keySeparator: false,

    interpolation: {
      escapeValue: false, // XSS 공격을 방지하기 위한 설정
      formatSeparator: ","
    },

    react: {
      wait: true
    }
  });

export default i18n;

i18next를 초기화하고, React 애플리케이션에 통합한다.
위의 설정에서 resources는 언어별로 번역문을 정의하는 부분이고 lng는 기본 언어를 설정하는 부분이다.

3. 번역을 적용할 컴포넌트에서 사용

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

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

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

  return (
    <div>
      <button onClick={() => changeLanguage('en')}>en</button>
      <button onClick={() => changeLanguage('kr')}>kr</button>
      <h2>{t('Welcome to React')}</h2>
    </div>
  );
}

export default App;

번역이 필요한 React 컴포넌트에서 useTranslation 훅을 사용하여 번역을 적용한다.
t 함수는 번역문을 가져오는 함수이다. 이 함수에 번역하려는 키를 전달해 언어를 바꾸는 버튼을 클릭하면 해당 언어로 번역된 문장을 볼 수 있다.

profile
오늘은 무슨 오류를 만날까?! 널 만나러 가는 길~ LOL

0개의 댓글