React Native에서 다국어 지원하는 법을 안내합니다.
다국어 지원을 위해 다음의 라이브러리를 사용합니다.
i18next
i18n은 JSON 파일에 각 언어별 번역을 저장하고, 이를 키-값 쌍으로 관리하며, 앱의 현재 언어 설정에 따라 적절한 번역을 동적으로 불러와 표시함으로써 다국어 지원을 구현합니다.
react-i18next
react-i18next는 i18next를 기반으로 하는 React / React Native를 위한 국제화 프레임워크입니다.(hooks 지원)
react-native-localize
react-native-localize는 React Native 앱 현지화를 위한 도구 상자입니다. (디바이스 시스템 언어, 숫자 서식, 통화 코드 획득 등)
yarn add i18next react-i18next react-native-localize
작성일 기준 버전
i18next: v23.16.0
react-i18next: v15.0.3
react-native-localize: v3.2.1
App.tsx
├── core
├── i18n.ts
└── locales
├── en.json
├── ko.json
i18n.ts : 라이브러리를 초기화합니다
locales : 다국어 파일 상위 폴더
en.json
{
"message": "Hello"
}
ko.json
{
"message": "안녕하세요"
}
라이브러리를 초기화합니다
import i18n from 'i18next'
import { initReactI18next } from 'react-i18next'
import en from '../locales/en.json'
import ko from '../locales/ko.json'
import { getLocales } from 'react-native-localize'
i18n
.use(initReactI18next)
.init({
lng: getLocales()[0].languageCode, // 사용할 언어
fallbackLng: 'en', // 번역 불가 시 대체 언어
supportedLngs: ['en', 'ko'], // 지원 언어
compatibilityJSON: 'v3',
resources: {
en: {
translation: en,
},
ko: {
translation: ko,
},
},
})
init 옵션 중 'compatibilityJSON'을 명시적으로 'v3'으로 지정하지 않으면 다음과 같은 에러가 발생합니다.
i18next::pluralResolver: Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling
다국어 처리 예시입니다.
function App(): React.JSX.Element {
const { t } = useTranslation()
return (
<SafeAreaView>
<Text>{t('message')}</Text>
</SafeAreaView>
)
}
디바이스 언어 설정에 따라 'Hello' 혹은 '안녕하세요'가
화면에 출력됩니다.