React

Global Message

다국어 구현 및 공용 메시지, 상수 사용에 대한 내용입니다.

Overview

해당 기능은 공통업무 기능입니다. 다음과 같이 미리 준비된 Boilerplate confy-app 형태로 제공됩니다.
다국어 구현은 react-i18next 라이브러리를 사용하여 구현되어 있습니다.

Usage

메시지 데이터 구조

1) pure-value

평문 데이터 메시지 예시

type Messages = {
key: string
value: string
}
// 메시지 샘플 데이터 영문
const messagesEn_ = {
MSG000001: 'save',
MSG000002: 'cancel',
MSG000003: 'login',
MSG000004: 'password',
MSG000005: 'title',
MSG000006: 'email',
MSG000007: 'English',
MSG000008: 'Enter the {{0}}', // <- 보간법(Interpolation) 예시
MSG000009: '{{0}} must be greater than {{1}}' // <- 보간법(Interpolation) 예시
}
// 메시지 샘플 데이터 한글
const messagesKo_ = {
MSG000001: '저장',
MSG000002: '취소',
MSG000003: '로그인',
MSG000004: '비밀번호',
MSG000005: '타이틀',
MSG000006: '이메일',
MSG000007: '한국어',
MSG000008: '{{0}}를 입력해 주세요', // <- 보간법(Interpolation) 예시
MSG000009: '{{0}}보다 크고 {{1}}보다 작은 수를 입력하세요' // <- 보간법(Interpolation) 예시
}

2) api-value

http://api.backendurl.com/message/kr 메시지 api 응답 예시

type MessagesResponse = {
id: number
locale: string
key: string
value: string
}
// 메시지 샘플 데이터 영문
url: api-url/message/en
{
"data": [
{
"id": 10,
"key": "MSG000001",
"value": "save",
"locale": "en"
},
...
{
"id": 18,
"key": "MSG000009",
"value": "{{0}} must be greater than {{1}}",
"locale": "en"
}
],
"result": {
"statusCode": 200,
"message": "SUCCESS",
"timestamp": "2025-04-18T02:10:49.752Z"
}
}
...

메시지 공통기능 구성 요소

아래 예시는 react-i18next 사용을 위한 기본 구조 입니다.

─── src
    ├── pages
    │   └── menu1/pages/page3.tsx // 예제 페이지
    ├── shared/i18n/i18n.ts       // i18n 설정 및 초기화 모듈
    │   
    └── main.ts                   // I18nextProvider 제공        

초기화 기능 설명

아래 예시는 메시지 파일 기본 구조에 대한 예시입니다.

/src/shared/i18n/i18n.ts

export default async function i18nInstance() {
const messagesEn = await fetchMessages('en') // <- 메시지 api
const messagesKo = await fetchMessages('kr') // <- 메시지 api
i18n
.use(LanguaeDetector) // 사용자 언어 탐지
.use(initReactI18next) // i18n 객체를 react-18next에 전달
.init({
resources: {
en: {
translation: messagesEn
},
ko: {
translation: messagesKo
}
},
...
})
return i18n
}

컴포넌트 내 사용 예시

/src/pages/menu1/pages/page3.tsx

import { useTranslation } from 'react-i18next'
function LanguageToggle() {
const { i18n } = useTranslation()
const changeLanguage = (language: string) => {
i18n.changeLanguage(language)
}
return (
<div>
<button onClick={() => changeLanguage('en')}>English</button>
<button onClick={() => changeLanguage('ko')}>한국어</button>
</div>
)
}
export default function Page3() {
const { t } = useTranslation()
return (
<>
<div>국제화 메시지 테스트</div>
<div>{t('MSG000001')}</div>
<div>{t('MSG000002')}</div>
...
<h1>`t(MSG000008) 인수 한개 case` {t('MSG000008', { 0: 'name' })}</h1>
<h1>`t(MSG000009) 인수 여러개 case` {t('MSG000009', { 0: 1, 1: 2 })}</h1>
<LanguageToggle />
</>
)
}

참고