Building a Multi-Language App with React JS

Table of Contents

Introduction

React JS is a popular JavaScript library used for building user interfaces. It provides a component-based approach to web development, making it easy to create reusable and modular UI components. In this article, we will explore how to build a multi-language app using React JS. By allowing users to switch between different languages, you can enhance the accessibility and usability of your application.

Setting up the React App

To get started, make sure you have Node.js installed on your system. You can check your Node.js version by running the command node -v in your terminal. Once you have Node.js installed, you can create a new React app using the create-react-app command. Open your terminal and run the following command:

npx create-react-app multi-language-app

This command will create a new directory called multi-language-app and set up a basic React app inside it. Navigate into the app directory using the command cd multi-language-app.

Adding Language Support

To add language support to our React app, we will use the i18next library along with its React bindings, react-i18next. i18next is a powerful internationalization library that supports multiple languages and provides features like translation, interpolation, and pluralization.

Start by installing the required dependencies. In your terminal, run the following command:

npm install i18next react-i18next i18next-http-backend

Once the dependencies are installed, create a new directory called locales in the src directory. Inside the locales directory, create a new file named en.json to hold the English translations. Add the following content to the en.json file:

{
  "greeting": "Hello, World!"
}

Similarly, create a file named fr.json inside the locales directory for French translations. Add the following content to the fr.json file:

{
  "greeting": "Bonjour, le monde!"
}

Now, let’s create a new component called LanguageSelector that allows the user to switch between languages. In the src directory, create a new file named LanguageSelector.js and add the following code:

import React from 'react';
import { useTranslation } from 'react-i18next';

const LanguageSelector = () => {
  const { i18n } = useTranslation();

  const handleChangeLanguage = (event) => {
    i18n.changeLanguage(event.target.value);
  };

  return (
    <div>
      <select onChange={handleChangeLanguage}>
        <option value="en">English</option>
        <option value="fr">French</option>
      </select>
    </div>
  );
};

export default LanguageSelector;

The LanguageSelector component uses the useTranslation hook from react-i18next to access the translation functionality. It renders a <select> element with options for English and French languages. When the user selects a language, the handleChangeLanguage function is called, which changes the language using the changeLanguage method provided by i18next.

Implementing Language Switching

Now, let’s modify the existing App component to display the translated greeting based on the selected language. Open the src/App.js file and update the code as follows:

import React from 'react';
import { useTranslation } from 'react-i18next';
import LanguageSelector from './LanguageSelector';

const App = () => {
  const { t } = useTranslation();

  return (
    <div>
      <LanguageSelector />
      <h1>{t('greeting')}</h1>
    </div>
  );
};

export default App;

In the modified App component, we import the useTranslation hook and the LanguageSelector component. The useTranslation hook provides the t function, which we use to translate the greeting key. The translated greeting will be displayed inside the <h1> element.

Setting up Translation Loading

To load the translations from the locales directory, we need to configure i18next. Create a new file named i18n.js in the src directory and add the following code:

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import Backend from 'i18next-http-backend';

i18n
  .use(Backend)
  .use(initReactI18next)
  .init({
    fallbackLng: 'en',
    debug: true,
    interpolation: {
      escapeValue: false,
    },
    backend: {
      loadPath: '/locales/{{lng}}/{{ns}}.json',
    },
  });

export default i18n;

In the i18n.js file, we import i18n, initReactI18next, and i18next-http-backend. We configure i18n to use the backend loader, specify the fallback language as English, and enable debugging. The backend option specifies the path pattern for loading translation files.

Integrating i18n with the App

To integrate the i18n instance with our app, open the src/index.js file and update the code as follows:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import i18n from './i18n';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

In the modified index.js file, we import the i18n instance and pass it to the I18nextProvider component, which wraps our App component. This ensures that the translations are available throughout the app.

Running the App

To run the app and see the language switching in action, open your terminal and navigate to the root directory of your project. Run the following command:

npm start

This command starts the development server, and you can access the app in your browser at http://localhost:3000. You should see a language selector with options for English and French. Changing the selected language will update the greeting message accordingly.

Conclusion

In this article, we explored how to build a multi-language app with React JS. We used the i18next library along with the react-i18next bindings to enable translation and language switching. By following the steps outlined in this article, you can enhance the user experience of your React app by providing support for multiple languages.

Remember to organize your translations in separate JSON files and make them available through the i18next configuration. Additionally, you can customize the language selector component and add more translations to suit your specific application requirements. Happy coding!

Command PATH Security in Go

Command PATH Security in Go

In the realm of software development, security is paramount. Whether you’re building a small utility or a large-scale application, ensuring that your code is robust

Read More »
Undefined vs Null in JavaScript

Undefined vs Null in JavaScript

JavaScript, as a dynamically-typed language, provides two distinct primitive values to represent the absence of a meaningful value: undefined and null. Although they might seem

Read More »