사내 서비스를 localization하면서 사용했던 rext-i18next의 사용법을 정리한다.
클래스 컴포넌트에서 사용했다.
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;
웹사이트에 텍스트가 많으면 번역 파일을 분리해서 작성하는 것이 보기 편하다. 컴포넌트 기준으로 분리해서 만들었다.
// card_trans.js
export const card = {
en: {
card_trans: {
title: 'Card',
}
},
ko: {
card_trans: {
title: '카드',
}
}
}
i18n.t('inputYourKey')
타이핑이 적어서 편리하다.
복잡한 텍스트일경우 다른 방법을 사용한다. (2번 확인)
i18n.t('key', {value: 10})
값은 {{value}}입니다.
<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>
이 된다.
변수랑 사용하는 방법
<Trans values={{value: 30}}/>
{{value}}입니다.
<br/>
태그는<Trans></Trans>
안에 적으면 적용된다.<b>
태그의 경우 <strong>
으로 적으면 적용된다.