[react] 다국어 처리(react-i18next) 적용하기

[react] 다국어 처리(react-i18next) 적용하기

사용 패키지. bootstrap 은 디자인을 깔끔하게 보이게 하기위해 추가

npm install i18next --save npm install react-i18next --save npm install react-bootstrap --save

프로젝트는 다음과 같이 구성했다.

i18n.js 파일 생성 및 옵션설정

import i18n from "i18next" import {initReactI18next} from "react-i18next"; import translationEn from './translation.en' import translationKo from './translation.ko' const resource = { en: { translation: translationEn }, ko: { translation: translationKo } }; i18n .use(initReactI18next) // passes i18n down to react-i18next .init({ resources: resource, lng: "ko", fallbackLng: 'ko', // ns: ['translation'], // defaultNS: "translation", debug: true, keySeparator: false, // we do not use keys in form messages.welcome interpolation: { escapeValue: false // react already safes from xss } }); export default i18n;

다국어를 파일별로 관리하고, 그것을 resource에 넣는다. 이렇게하면 확정성이 용이할거라 생각했다.

translationXX 파일 내부는 다음과 같이 json으로 구성했다

영문

{ "hello": "Hello !!" }

한글

{ "hello": "안녕" }

위의 파일 내용을 resource 에 넣고, init 옵션 중 resources에 집어넣었다.

그리고 debug를 true 하기를 추천한다.(안나오면 왜 안나오는지 알 방법이 없다.)

기타 필요한 것은 모두 넣은거 같다.

그럼 이 파일을 index.js 파일에 추가해야 한다.

index.js 파일구성을 보면 다음과 같다.

MainComponent.jsx

import React, {Component} from "react"; import {withTranslation} from "react-i18next"; import i18next from "../config/lang/i18n"; import {Dropdown} from "react-bootstrap"; class MainComponent extends Component { ... } export default withTranslation()(MainComponent);

App.jsx

import React from 'react'; import logo from './logo.svg'; import './App.css'; import 'bootstrap/dist/css/bootstrap.min.css' import MainComponent from "./component/MainComponent"; function App() { return ( ); } export default App;

이제 MainComponent에 내용을 추가한다.

우선 i18n을 적용하기 위해서는 withTranslation() 을 실행하고 export 해야한다.

... export default withTranslation()(MainComponent);

다음은 공식페이지에서의 설명이다

The withTranslation is a classic HOC (higher order component) and gets the t function and i18n instance inside your component via props.

t와 i18n을 인스턴스 하기 위해 필요하다고 하니 꼭 넣어주자.

사용하는 방법은 다음과 같다

import React, {Component} from "react"; import {withTranslation} from "react-i18next"; import i18next from "../config/lang/i18n"; class MainComponent extends Component { ... render() { const {t} = this.props; return ( {t('hello')} {t('helloTest')} ) } ... }

이렇게 하면 hello 라고 등록된 값을 가져온다.

등록된 message가 없으면 console 창에 다음과 같은 문구가 뜨고, 변수명을 그대로 노출한다.

참고로 설정에서 debug 모드를 true로 해두지 않으면 콘솔창에 경고문을 출력하지 않는다.

# 브라우저 콘솔창을 보면 다음 문구가 뜬다 i18next::translator: missingKey ko translation helloTest helloTest

# bootstrap 의 DropDown 을 사용하여 변경해보기

이번에는 어느 사이트에서나 본듯한 언어변경을 시도해보자. 여기서는 DropDown을 사용하여 변경하도록 한다.

그리고 변경되면 DropDown 의 텍스트도 바뀌도록 한다

import React, {Component} from "react"; import {withTranslation} from "react-i18next"; import i18next from "../config/lang/i18n"; import {Dropdown} from "react-bootstrap"; class MainComponent extends Component { state = { languageTitle: "한국어" } changeLanguage = (e) => { // 언어변경 i18next.changeLanguage(e.split(',')[0]); // 이름변경 this.setState({ "languageTitle": e.split(',')[1] }) } render() { const {t} = this.props; return ( {this.state.languageTitle} 한국어 ENGLISH {t('hello')} ) } } export default withTranslation()(MainComponent);

코드를 보면 title 부분을 state.languageTitle 을 보게 했다. 그래야 키를 클릭했을때 텍스트를 변경할 수 있기 때문이다.

hadler는 changeLanguage 에서 하도록 했는데 자세히 보면 문자열을 잘라서 쓴다. eventKey를 사용할때 parameter를 가변적으로 전달할 수 있게끔 하면 좋겠는데 아쉽게 찾지 못했다. 제목역시 직접 파라미터로 받을 것이므로 eventKey 에 직접 등록한다.

changeLanguage = (e) => { // 언어변경 i18next.changeLanguage(e.split(',')[0]); // 이름변경 this.setState({ "languageTitle": e.split(',')[1] }) }

이제 화면을 보면 다음과 같이 뜬다. DropDown 의 값을 각각 클릭해 보자.

코드는 github에 올려두었다.

https://github.com/lemontia/sample-react-i18next

끝.

참조:

공식페이지:

https://react.i18next.com/getting-started

https://99geo.tistory.com/9

https://github.com/i18next/react-i18next/issues/625

https://velog.io/@sss5793/%EA%B5%AD%EC%A0%9C%ED%99%94-%EB%9D%BC%EC%9D%B4%EB%B8%8C%EB%9F%AC%EB%A6%AC-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0

https://sg-choi.tistory.com/241

from http://lemontia.tistory.com/924 by ccl(A) rewrite - 2020-03-14 14:54:14

댓글

이 블로그의 인기 게시물

[React] - 18) 프로젝트 빌드하기(+코드 스플리팅)

입트영(2020.03.23) - Iced Drinks / 아이스 음료

Redux + React