[22-06-06 TIL] react i18next 사용법

O2o2✨·2022년 6월 6일
0

TIL

목록 보기
12/25

사내 서비스를 localization하면서 사용했던 rext-i18next의 사용법을 정리한다.

클래스 컴포넌트에서 사용했다.

1. 설치

npm install i18next react-i18next i18next-browser-languagedetector
를 터미널에 입력한다.

i18n.js파일을 만든 후 코드를 작성한다.

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';

i18n
  // detect user language
  // learn more: https://github.com/i18next/i18next-browser-languageDetector
  .use(LanguageDetector)
  // pass the i18n instance to react-i18next.
  .use(initReactI18next)
  // init i18next
  // for all options read: https://www.i18next.com/overview/configuration-options
  .init({
    debug: true,
    fallbackLng: 'en',
    interpolation: {
      escapeValue: false, // not needed for react as it escapes by default
    },
    resources: {
      en: {
        translation: {
          // 번역을 정리한 파일의 객체를 넣는다.
          // 예) ...card.en,
        }
      }
      ko: {
      	translation: {
        	// 예) ...card.ko,
    	}
      }
    }
  });

export default i18n;

2. 번역 파일 생성

웹사이트에 텍스트가 많으면 번역 파일을 분리해서 작성하는 것이 보기 편하다. 컴포넌트 기준으로 분리해서 만들었다.

// card_trans.js
export const card = {
  en: {
  	card_trans: {
      title: 'Card',
    }
  },
  ko: {
  	card_trans: {
      title: '카드',
    }
  }
}

3. 사용법

방법1. i18n.t() 사용

i18n.t('inputYourKey')

타이핑이 적어서 편리하다.
복잡한 텍스트일경우 다른 방법을 사용한다. (2번 확인)

  • 변수와 사용하는 방법
    • jsx: i18n.t('key', {value: 10})
    • json 번역 파일: 값은 {{value}}입니다.
    • 출력: 값은 10입니다.

방법2. Trans component사용

<Trans i18nKey={'inputYourKey'} >
  • <div>안녕<span>하세요</span></div>와 같이 안에 다른 element가 있는 경우 Trans의 components라는 props에 배열을 전달해주면 된다.

    • jsx: <Trans components={[<div></div>, <span></span>]}/>

    • json 번역 파일: <0>안녕<1>하세요</1></0>

      <0>은 배열의 0번째 원소인 <div>가 되고 <1>은 1번째 원소인 <span>이 된다.

  • 변수랑 사용하는 방법

    • jsx: <Trans values={{value: 30}}/>
    • json 번역 파일: {{value}}입니다.

4. 기타

  • App > localStorage에서 i18next가 en인지 ko인지 확인할수있다.
    그 설정에 따라 한영변환이 된다.
  • <br/>태그는<Trans></Trans>안에 적으면 적용된다.
  • <b>태그의 경우 <strong>으로 적으면 적용된다.

5. 참고

profile
리액트 프론트엔드 개발자입니다.

0개의 댓글