React에서 i18n을 구현할 때 가장 많이 사용되는 라이브러리는 react-i18next이다.
# npm
npm install react-i18next i18next
# pnpm
pnpm add react-i18next i18next
# yarn
yarn add react-i18next i18next
TypeScript 프로젝트라면 추가 설치가 필요함.
# npm
npm install --save-dev @types/i18next
# pnpm
pnpm add -D @types/i18next
# yarn
yarn add -D @types/i18next
// src/i18n.js
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import en from './locales/en.json';
import ko from './locales/ko.json';
i18n.use(initReactI18next).init({
resources: {
en: { translation: en },
ko: { translation: ko },
},
lng: 'ko', // 기본 언어
fallbackLng: 'en',
interpolation: {
escapeValue: false, // React는 XSS 방지 기능 있음
},
});
export default i18n;
// src/locales/en.json
{
"hello": "Hello",
}
// src/locales/ko.json
{
"hello": "안녕하세요",
}
App.js 또는 index.js에 다음과 같이 설정 파일을 import한다.
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './i18n'; // 설정 파일 import
import { useTranslation } from 'react-i18next';
function MyComponent() {
const { t, i18n } = useTranslation();
const changeLanguage = (lng) => {
i18n.changeLanguage(lng);
};
return (
<div>
<p>{t('hello')}</p>
<button onClick={() => changeLanguage('en')}>EN</button>
<button onClick={() => changeLanguage('ko')}>KO</button>
</div>
);
}
언어 저장 파일에서
// ko.json
{
"greeting": "안녕하세요, {{name}}님!"
}
사용할 때,
t('greeting', { name: '이든' }); // "안녕하세요, 이든님!"
이 정도 세팅을 하면 기본적인 다국어 처리가 가능했는데, 변수 삽입 부분은 제대로 적용되지 않을 때도 있었다. 리팩토링 후 새로운 기능을 소개하도록 하겠다!
글로벌로 뻗어나가는 고수 개발자...