김 양의 멋따라 개발따기

React로 언어 변환하기(react-i18next) 본문

React!

React로 언어 변환하기(react-i18next)

개발따라김양 2023. 1. 19. 11:02

1. 라이브러리 설치

//npm
npm install react-i18next --save 
//yarn
yarn add react-i18next

2. 언어별 json파일 만들기

//src/util/language/korean/page.json

{
    "about-who-1":"연구와 경험의 숙성 속 나의 성장이 팀과 회사의 성장으로 연결되어 함께 나란히 걸어 나아가는 우리는 어느덧 프로입니다. 좋아하는 일을 제일 잘하며 끼 많고 개성 넘치는 ’나’ 들이 모여 디자인과 홍보의 모든 일들에 산뜻하고 참신한 솔루션을 만들어 냅니다.",
}
//src/util/language/english/page.json

{
    "about-who-1":"We are professionals where our individual growth, based on research and experience, leads to the growth of our team and our company. We are unique and talented individuals, who love what we do, gathered to create solutions in all areas of design and promotion.",
}

 

 

 

3. index.js 파일 생성

//src/util/language/index.js

import i18n from "i18next"
import {initReactI18next} from "react-i18next"
import ko from "./korean/page.json"
import en from "./english/page.json"


const resource = {
    en : {
        translation: en
    },
    ko : {
        translation: ko
    }
}

i18n.use(initReactI18next).init({
    resources: resource,
    lang:"ko",
    fallbackLng: 'ko',
    debug: true,
    saveMissing: true,
   
},function(err) {
    if(err) console.error(err);
  })

  export default i18n;

 

4. index.js(최상위)에서 import 하기

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import {BrowserRouter} from "react-router-dom"
import "./util/language/index"

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
);

5. 사용하기

//언어 변환 버튼이 있는 header
import { useTranslation } from 'react-i18next'


const Header = () => {
 
  const { i18n } = useTranslation(['page']);

  const changelanguageToKo = () => i18n.changeLanguage('ko')
  const changelanguageToEn = () => i18n.changeLanguage('en')



  return (
    <Container>

        <p onClick={changelanguageToKo}>🌍ko</p>
        <p onClick={changelanguageToEn}>🌍En</p>

    </Container>
  );
};

export default Header;

 

//사용하는 컴포넌트
import { useTranslation } from 'react-i18next'

const AboutWho = () => {
  const { t } = useTranslation()

    return(
        <Container>
            <h2>who we are</h2>
            <p>{t("about-who-1")}</p>
        </Container>
    )
}

export default AboutWho

 

 

 

 

 

 

 

 

 

 

 

출처 : https://uiyoji-journal.tistory.com/74

 

[React.js로 만드는 Tech Blog] #5 언어 설정을 위한 react-i18next 라이브러리 사용하기/국제화 라이브러

2021/02/21 - [👩‍💻/React.js] - [React.js로 만드는 Tech Blog] #4 Window.scrollY/window.pageYOffset 2021/02/16 - [👩‍💻/React.js] - [React.js로 만드는 Tech Blog] #3 master 브랜치로 통합하기/github pages에 재배포하기 2021/02

uiyoji-journal.tistory.com