简体   繁体   中英

How to add multilingualism to my application using i18n React

import React from 'react';
import { Routes, Route } from 'react-router-dom';
import Home from './routes/Home';
import Pricing from './routes/Pricing';
import Portfolio from './routes/Portfolio';
import Booking from './routes/Booking';
import { withTranslation } from 'react-i18next';

import i18next from 'i18next';
import { initReactI18next } from 'react-i18next';
import en from './locales/en.json';
import fr from './locales/he.json';
import LanguageSwitcher from './LanguageSwitcher';

class App extends React.Component {
  componentDidMount() {
    i18next
      .use(initReactI18next)
      .init({
        resources: {
          en: {
        translation: en
      },
      he: {
        translation: he
      }
    },
    lng: 'en',
    fallbackLng: 'en',
    interpolation: {
      escapeValue: false
    }
  });
}

render() {
  const { t } = this.props;
  return (
    <>
      <LanguageSwitcher />
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/pricing" element={<Pricing />} />
        <Route path="/portfolio" element={<Portfolio />} />
        <Route path="/booking" element={<Booking />} />
      </Routes>
    </>
  );
}
}

export default withTranslation()(App);

If you're using the withTranslation HOC , you may have a look at this example :

// use hoc for class based components
class LegacyWelcomeClass extends Component {
  render() {
    const { t } = this.props;
    return <h2>{t('title')}</h2>;
  }
}
const Welcome = withTranslation()(LegacyWelcomeClass);

I would also suggest to checkout this guide about react-i18next.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM