다국어 i18next

airwalk·2024년 2월 16일
0

다국어 처리 방법

패키지 설치

yarn add react-i18next i18next-browser-languagedetector i18next

i18n config 설정

import detector from "i18next-browser-languagedetector";
import { initReactI18next } from "react-i18next";
import i18n from "i18next";
import translationKo from "./ko/translation.json";
import translationENG from "./en/translation.json";

import { setItem, getItem } from "helpers/localstorage";

const resources = {
  ko: {
    translation: translationKo,
  },
  en: {
    translation: translationENG,
  },
};

const language = getItem("I18N_LANGUAGE");
if (!language) {
  setItem("I18N_LANGUAGE", "ko");
}

i18n
  .use(detector) // 브라우저 언어 자동 감지
  .use(initReactI18next)
  .init({
    resources, 
    lng: getItem("I18N_LANGUAGE") || "ko", // 현재 언어 설정
    fallbackLng: "ko", // 지원되지 않는 언저 감지 될때 ko
    keySeparator: false, 
    interpolation: {
      escapeValue: false,
    },
  });
export default i18n;

  • keySeparator 옵션을 false로 했을 경우 아래와 같이 사용가능
# en
{
    "nav.dashboard": "dashboard",
}
# ko
{
    "nav.dashboard": "대시보드",
}

사용

import { useTranslation } from "react-i18next";
import i18n from "locales/i18n";

const App = () => {
  
  const { t } = useTranslation();
  
  return (
    <span>{t(`nav.dashboard`)}</span>
  )
  
}
 

0개의 댓글

관련 채용 정보