react-i18next 를 이용하려다 여러 글들을 봤는데 너무 어려워서 저처럼 초보도 알아볼 수 있게 정리를 해봤습니다.

 

app.js

import React, { Component } from "react";
import { withTranslation, Trans } from "react-i18next";
import PropTypes from "prop-types";
import Radio from "@material-ui/core/Radio";
import RadioGroup from "@material-ui/core/RadioGroup";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import FormControl from "@material-ui/core/FormControl";
import FormLabel from "@material-ui/core/FormLabel";
import Paper from "@material-ui/core/Paper";
import Grid from "@material-ui/core/Grid";
import Typography from "@material-ui/core/Typography";
import List from "@material-ui/core/List";
import ListItem from "@material-ui/core/ListItem";
import ListItemText from "@material-ui/core/ListItemText";
import Header from "./Header";

class App extends Component {
  state = {
    value: "en"
  };

  handleChange = event => {
    let newlang = event.target.value;
    this.setState(prevState => ({ value: newlang }));
    this.props.i18n.changeLanguage(newlang);
  };

  render() {
    const { t } = this.props;
    return (
      <div className="App">
        <Header />

        <div >
          <Grid container spacing={24}>
            <Grid item xs={12}>
                <div >
                  <FormControl
                    component="fieldset"
                  >
                    <FormLabel component="legend">Select Language</FormLabel>
                    <RadioGroup
                      aria-label="Gender"
                      name="gender1"
                      value={this.state.value}
                      onChange={this.handleChange}
                    >
              <FormControlLabel//  여기 value 값으로 실제 i18n에 있는 값을 불러옴 ko면 한국어
                        value="ko"
                        control={<Radio />}
                        label="Korean"
                      />
                      <FormControlLabel
                        value="en"
                        control={<Radio />}
                        label="English"
                      />
                      <FormControlLabel
                        value="jap"
                        control={<Radio />}
                        label="Japanese"
                      />

                      <FormControlLabel
                        value="hin"
                        control={<Radio />}
                        label="Hindi"
                      />
                      <FormControlLabel
                        value="fre"
                        control={<Radio />}
                        label="French"
                      />
                      <FormControlLabel
                        value="ger"
                        control={<Radio />}
                        label="German"
                      />
                    </RadioGroup>
                  </FormControl>
                </div>
              </Grid>
            <Grid item xs={12}>
              <Paper >
                <Typography variant="h3" gutterBottom>
                  <Trans> {t("Introduction")} </Trans>

                  <Typography variant="subtitle2" gutterBottom>
                    i18next{" "}
                    {t(
                      "is an internationalization-framework which offers a complete solution to localize your product from web to mobile and desktop"
                    )}             
                    {/* 위에 문장 처럼 i18n 적용 t()안에 치환 할 문자를 넣어 주시면 돼요 !  */}
                  </Typography>
                </Typography>
              </Paper>
            </Grid>
            <Grid item xs={6}>
              <Paper >
                <Typography variant="h6" gutterBottom>
                  {t("Advantages")}
                </Typography>

                    {/* 위에 문장 처럼 i18n 적용 t()안에 치환 할 문자를 넣어 주시면 돼요 !  */}
                <List dense={false}>
                  <ListItem>
                    <ListItemText>
                      {t("Plugins to detect the user language")}
                    </ListItemText>
                  </ListItem>
                       {/* 위에 문장 처럼 i18n 적용 t()안에 치환 할 문자를 넣어 주시면 돼요 !  */}
                  <ListItem>
                    <ListItemText>
                      {t("Plugins to load translations")}
                    </ListItemText>
                  </ListItem>

                  <ListItem>
                    <ListItemText>
                      {t("Optionally cache the translations")}
                    </ListItemText>
                  </ListItem>

                  <ListItem>
                    <ListItemText>
                      {t("Flexibility to use other packages")}
                    </ListItemText>
                  </ListItem>

                  <ListItem>
                    <ListItemText>
                      {t("Plugins to detect the user language")}
                    </ListItemText>
                  </ListItem>
                </List>
              </Paper>
            </Grid>
            <Grid item xs={6}>
            </Grid>
          </Grid>
        </div>
      </div>
    );
  }
}

// extended main view with translate hoc

App.propTypes = {
  classes: PropTypes.object.isRequired
};

export default withTranslation()(App);

Header.js

import React from "react";
import PropTypes from "prop-types";
import { withStyles } from "@material-ui/core/styles";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import Typography from "@material-ui/core/Typography";

const styles = {
  root: {
    flexGrow: 1
  }
};

function SimpleAppBar(props) {
  const { classes } = props;

  return (
    <div className={classes.root}>
      <AppBar position="static" color="primary">
        <Toolbar>
          <Typography variant="h5" color="inherit">
            리액트 i18n !
          </Typography>
        </Toolbar>
      </AppBar>
    </div>
  );
}

SimpleAppBar.propTypes = {
  classes: PropTypes.object.isRequired
};

export default withStyles(styles)(SimpleAppBar);

i18n.js

import i18n from "i18next";
import LanguageDetector from "i18next-browser-languagedetector";

i18n.use(LanguageDetector).init({
  // we init with resources
  resources: {

    ko: {
      translations: {
      Introduction: "소개",
       "is an internationalization-framework which offers a complete solution to localize your product from web to mobile and desktop":
        "소개입니다",
      "Plugins to detect the user language":
        "소개에에에엥",
      "Plugins to load translations": "소개",
      "Optionally cache the translations": "소개",
        Advantages: "Advantages",
        "Flexibility to use other packages": "소개"
      }
    },


    en: {
      translations: {
        Introduction: "Introduction",
        "is an internationalization-framework which offers a complete solution to localize your product from web to mobile and desktop":
          "is an internationalization-framework which offers a complete solution to localize your product from web to mobile and desktop",
        "Plugins to detect the user language":
          "Plugins to detect the user language",
        "Plugins to load translations": "Plugins to load translations",
        "Optionally cache the translations":
          "Optionally cache the translations",
        Advantages: "Advantages",
        "Flexibility to use other packages": "Flexibility to use other packages"
      }
    },
    jap: {
      translations: {
        Introduction: "前書き",
        "is an internationalization-framework which offers a complete solution to localize your product from web to mobile and desktop":
          "Webからモバイルとデスクトップに製品をローカライズするための完全なソリューションを提供する国際化フレームワークです",
        "Plugins to detect the user language":
          "ユーザー言語を検出するためのプラグイン",
        "Plugins to load translations": "翻訳をロードするためのプラグイン",
        "Optionally cache the translations": "必要に応じて翻訳をキャッシュする",
        Advantages: "利点",
        "Flexibility to use other packages": "他のパッケージを使用する柔軟性"
      }
    },

    hin: {
      translations: {
        Introduction: "प्रस्तावना",
        "is an internationalization-framework which offers a complete solution to localize your product from web to mobile and desktop":
          "एक अंतर्राष्ट्रीयकरण - ढांचा है जो आपके उत्पाद को वेब से मोबाइल और डेस्कटॉप पर स्थानांतरित करने का एक संपूर्ण समाधान प्रदान करता है",
        "Plugins to detect the user language":
          "उपयोगकर्ता भाषा का पता लगाने के लिए प्लगइन्स",
        "Plugins to load translations": "अनुवाद लोड करने के लिए प्लगइन्स",
        "Optionally cache the translations": "वैकल्पिक रूप से अनुवाद कैश करें",
        Advantages: "लाभ",
        "Flexibility to use other packages":
          "अन्य पैकेजों का उपयोग करने के लिए लचीलापन"
      }
    },

    ger: {
      translations: {
        Introduction: "Einführung",
        "is an internationalization-framework which offers a complete solution to localize your product from web to mobile and desktop":
          "ist ein Internationalisierungs-Framework, das eine Komplettlösung für die Lokalisierung Ihres Produkts vom Web auf das Handy und den Desktop bietet",
        "Plugins to detect the user language":
          "Plugins zur Erkennung der Benutzersprache",
        "Plugins to load translations": "Plugins zum Laden von Übersetzungen",
        "Optionally cache the translations":
          "Optional die Übersetzungen zwischenspeichern",
        Advantages: "Vorteile",
        "Flexibility to use other packages":
          "Flexibilität zur Verwendung anderer Pakete"
      }
    },
    fre: {
      translations: {
        Introduction: "Introduction",
        "is an internationalization-framework which offers a complete solution to localize your product from web to mobile and desktop":
          "est un cadre d'internationalisation qui offre une solution complète pour localiser votre produit du Web au mobile et au bureau",
        "Plugins to detect the user language":
          "Plugins pour détecter la langue de l'utilisateur",
        "Plugins to load translations": "Plugins pour charger les traductions",
        "Optionally cache the translations":
          "Cachez éventuellement les traductions",
        Advantages: "Les avantages",
        "Flexibility to use other packages":
          "Flexibilité d'utiliser d'autres packages"
      }
    }
  },
  fallbackLng: "en",
  debug: true,

  // have a common namespace used around the full app
  ns: ["translations"],
  defaultNS: "translations",

  keySeparator: false, // we use content as keys

  interpolation: {
    escapeValue: false, // not needed for react!!
    formatSeparator: ","
  },

  react: {
    wait: true
  }
});

export default i18n;

index.js

import React from "react";
import ReactDOM from "react-dom";
import { I18nextProvider } from "react-i18next";

import i18n from "./i18n";
import App from "./app";

// wrap the app in I18next Provider with the configuration loaded from i18n.js
ReactDOM.render(
  <I18nextProvider i18n={i18n}>
    <App />
  </I18nextProvider>,
  document.getElementById("root")
);

 

 

결과 

한글번역

 

영어번역
일본번역

 

 

 

이렇게 i18next로 다국어 처리를 해봤습니다 폴더구조는 정말 간단하게 

 

이렇게만 정해주시면 됩니다.

 

추가로 설명할 부분은 일단 i18n에 ko, en, jp 별로 코딩을 합니다. 그리구 app.js 최상위 파일에서 import 해주는 방식으로  

{t(

"is an internationalization-framework which offers a complete solution to localize your product from web to mobile and desktop"

)}

 

이런식으로 {t( 치환 할 문자 )}를 넣어주시면 됩니다 !

저처럼 초보개발자인데 i18next를 사용하고싶으신분들은 코드 보면서 코드리뷰해보면 이해가 가실 것 같습니다 

감사합니다 :) 많은 조언도 주세요 피드백 받고있습니다.

 

 

참고 사이트 : 외국 사이트에서 번역 + 추가 개발을 한 것인데 사이트를 찾으면 올리겠습니다ㅜㅜ

 

git에 코드 올라가있습니다 !

 

git주소 : https://gitlab.com/99geometry/i18n

'React' 카테고리의 다른 글

React + Nodejs 서버 연동하기 (초보용)  (0) 2019.08.13
React material-ui 로 customizing 해보기 !  (0) 2019.08.13
Babel 이란 ?  (0) 2019.08.12
리액트로 웹에서 Hello world 보여주기 !  (0) 2019.08.06
React 기초 설정  (0) 2019.08.06

+ Recent posts