참고)
※ 배워가는 입장이어서 틀린 것이 있다면 댓글로 알려주세용!
소개
최근 프로젝트에서 리액트에서의 다국어세팅을 해야 되는 상황이 발생해서 관련 라이브러리를 찾다가 i18next를 찾게 되었습니다.
그래서 이번에 i18next를 공부하면서 사용법을 알아보려고 합니다.
사용법
$ npm install react-i18next i18next --save
기본적으로 i18next와 react에서 사용할 react-i18next를 설치해 줍니다.
그 후에 i18next를 사용하기 위해서는 기본적으로 설치가 필요합니다.
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
i18n
.use(initReactI18next) // react-i18next 를 설치해줍니다.
.init({
fallbackLng: "en", // 기본 언어를 제공할수 없을때 대체언어
lng: "en", // 기본언어
debug: true, // 디버깅
resources: { // 언어설정
},
});
import App from "./App";
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
root.render(
<StrictMode>
<App />
</StrictMode>
);
기본적으로 이렇게 설정을 해줍니다.
use(initReactI18next)는 react-i18next을 사용하겠다는 의미로 보시면 되고
.init({})의 속성들은 여러 개 있으나 대표적으로
fallbackLng는 기본 언어를 제공할 수 없을 때 대체언어 (string 타입입니다.)
lng 현재 설정 언어입니다. (string 타입입니다.)
debug 디버깅을 할 건지 boolean 타입으로 설정해 줍니다.
resources는 이제 ko 한국어 jp 일본어 en 영어 등 여러 가지 언어로 설정하여 텍스트를 수정하게 도와줍니다.
이제 resources에 변화할 텍스트를 넣고 확인해 보도록 하겠습니다.
i18n
.use(initReactI18next) // react-i18next 를 설치해줍니다.
.init({
fallbackLng: "ko", // 기본 언어를 제공할수 없을때 대체언어
lng: "ko", // 기본언어
debug: true, // 디버깅
resources: {
ko: {
translation: {
main: "메인 페이지",
},
},
en: {
translation: {
main: "Main Page",
},
},
},
});
저는 ko, en을 이렇게 설정을 하였습니다.
바뀔 언어를 넣을 때는 translation를 넣어주고 그 안에 객체를 넣어줘야 합니다.
import "./styles.css";
export default function App() {
return (
<div className="App">
<button>한국어</button>
<button>영어</button>
<p>텍스트가 변합니다.</p>
</div>
);
}
이제 p 태그의 텍스트가 변합니다. 이 부분을 다국어 처리해서 한국어 버튼, 영어 버튼을 만들어 변화하는 과정을 확인해 보겠습니다.
import { useTranslation } from "react-i18next";
import "./styles.css";
export default function App() {
const { t, i18n } = useTranslation();
return (
<div className="App">
<button
onClick={() => {
i18n.changeLanguage("ko");
}}
>
한국어
</button>
<button
onClick={() => {
i18n.changeLanguage("en");
}}
>
영어
</button>
<p>{t("main")}</p>
</div>
);
}
useTranslation는 react-i18next의 컴포넌트를 불러오는데 여기서 t와 i18n가 존재합니다
t는 resources 안에 있는 데이터를 불러오는 컴포넌트입니다.
i18n는 여러 hook을 가지고 있는 컴포넌트입니다.
대표적으로 changeLanguage()을 가지고 있는데 여기 안에 바뀔 언어를 넣어주면 언어가 수정되면서 t() 안에 있는 언어를 수정해 줍니다.
이것으로 간단하게 다국어 세팅을 하는 것을 배워보았습니다.
이것 관련된 거로 여러 가지를 활용하면 더 편하게 다국어 처리를 할 수 있지 않을까 생각이 듭니다. : )
Introduction - i18next documentation
locize: Now, 'locize' is your efficient manager in charge of organizing and streamlining the translation process. It keeps all your language versions organized and ensures they're always accurate and up-to-date. So, if you want to introduce a new product o
www.i18next.com
Introduction - react-i18next documentation
Hello {{name}} , you have {{count}} unread message(s). Go to messages.
react.i18next.com
'React' 카테고리의 다른 글
React 에서 카카오맵을 사용해보자 (0) | 2024.04.07 |
---|---|
React 에서 로딩화면을 만들어보자! (Suspense) (0) | 2024.04.07 |
CRA 와 Vite 의 차이 (0) | 2024.03.30 |
[EmailJS] React로 간단하게 이메일을 보내보자 (2) | 2024.03.23 |
React 란? (0) | 2024.01.22 |