Tag Archive for: language

Basic translator using Vanilla JavaScript

Create a multilingual React website

First of all create a react app ready to go

create-react-app MY-WEBSITE

This will create a react app with everything configured.

npm start

Add i18next package

npm i -S i18next

This will let us do our website/app internationalization.

Set up your I18next file

Create a i18n.js file in the src folder with this code:

import i18n from 'i18next';

i18n
  .init({
    fallbackLng: 'en',
    lng: navigator.language.split('-')[0],
    debug: true,
    resources: {
      en: {
        translation: {
          "Hola": "Hello",
          "Adiós": "Bye"
        }
      }
    }
  });

export default i18n;

Finally, indicate which text you want to translate

Import your i18n.js and use its t function to indicate where it should be the internationalization.

import React, { Component } from 'react';
import logo from './logo.svg';
import i18n from './i18n';
import './App.css';

let t = i18n.t.bind(i18n);

class App extends Component {
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>{t("Hola")}</h2>
        </div>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

export default App;