How to use i18n

이지·2021년 7월 19일
0

React

목록 보기
7/7

internationalization 을 i18n으로 나타낸 것이며, 웹사이트를 구축할 때 다국어처리에 자주 쓰이는 라이브러리. 글로벌 서비스를 지향하는 서비스를 구축하고 있기 때문에 현재 작업중인 모든 프로덕트에 i18n이 사용되고 있다.

1. i18n.ts file

import i18n from "i18next";
import { initReactI18next, useTranslation } from "react-i18next";
//import the json files
import tranEn from "../src/locales/files/en.json";
import tranKo from "../src/locales/files/ko.json";

const resources = {
  en: {
    translation: tranEn,
  },
  ko: {
    translation: tranKo,
  },
};

//localstorage 에 settings 가 있다면, 가져오고, 아니면 en를 기본 언어로 한다. 
const storedData: string | null = window.localStorage.getItem("settings");
const settings = JSON.parse(storedData);
i18n.use(initReactI18next).init({
  resources,
  lng: settings ? settings.locale : "en",
  fallbackLng: "en",
  interpolation: {
    escapeValue: false,
  },
});

// how to translate texts in components
function App = () =>{
const {t, i18n} = useTranslation()

//i18n language setting 을 바꿔주는 함수 changeLanguage
const changeLanguage=(lang)=>{i18n.changeLanguage(lang)}

return 
  (<>
<h1>{t("Auth.hello")}</h1> 
{[ko,en,fr].map((el)=> (<button onClick={()=>changeLanguage(el)}>click</button>))}
 </>)
}
// dot notation 을 사용하여 카테고리를 분류하여 접근도 가능하다. ex)Auth.hello 

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

profile
이지피지레몬스퀴지🍋

0개의 댓글