Multi-language translator using Google Translate in a React application(Begginner Project)

Hashirmughal
5 min readApr 21, 2024

--

In today’s world, having a translator on websites is super important. It helps everyone understand the site, no matter what language they speak. This means more people can use the site, which is great for making connections and growing the website.
In this tutorial, we will create a React component that uses the Google Translate Api

Prerequisites:

  1. Basic Knowledge of React: Understand the fundamentals of React.js, including components, state, props, and JSX.
  2. Create React App: Familiarity with creating React applications using Create React App for quick setup and development.

3. React Router Dom: Understanding of React Router Dom for managing routes and navigation within the React application.

To get started, we need to install the following libraries:

To create a multi-language translator using Google Translate in a React application, you can follow these steps:

  1. Set Up Your React App: Create a new React application if you haven’t already. You can use Create React App for this.
npx create-react-app multi-language
cd multi-language
npm start
  1. Install pakage for routing in React “react-router-dom”

You can install these libraries by running the following command in your project’s root folder:

npm i react-router-dom

Create the App component

import logo from './logo.svg';
import './App.css';

function App() {
return (
<div className="App">
<h1>
hello world
</h1>
</div>
);
}

export default App;

Create the Home component

import React from "react";

const Home = () => {
return (
<>
<h1>Home</h1>
<p>This is the Business page content.</p>
</>
);
};

export default Home;

Create the About component

import React from "react";

const About = () => {
return (
<>
<h1>About Us</h1>
<p>This is the about us page content.</p>
</>
);
};

export default About;

Create header component

import { Link } from "react-router-dom";

const Header = () => {
return (
<header>
<nav>
<ul style={{ display: "flex", gap: "10px" ,listStyle:"none"}}>
<li><Link to='/home'>Home</Link></li>
<li><Link to='/about-us'>AboutUs</Link></li>
</ul>
</nav>
</header>
);
};

export default Header;

Create TranslateComponent

import React, { useEffect, useRef } from "react";

const TranslateComponent = () => {
const googleTranslateRef = useRef(null);

useEffect(() => {
let intervalId = null;
const checkGoogleTranslate = () => {
if (window.google && window.google.translate && window.google.translate.TranslateElement.InlineLayout) {
clearInterval(intervalId);
new window.google.translate.TranslateElement(
{
pageLanguage: "en",
includedLanguages: "af,ach,ak,am,ar,az,be,bem,bg,bh,bn,br,bs,ca,chr,ckb,co,crs,cs,cy,da,de,ee,el,en,eo,es,es-419,et,eu,fa,fi,fo,fr,fy,ga,gaa,gd,gl,gn,gu,ha,haw,hi,hr,ht,hu,hy,ia,id,ig,is,it,iw,ja,jw,ka,kg,kk,km,kn,ko,kri,ku,ky,la,lg,ln,lo,loz,lt,lua,lv,mfe,mg,mi,mk,ml,mn,mo,mr,ms,mt,ne,nl,nn,no,nso,ny,nyn,oc,om,or,pa,pcm,pl,ps,pt-BR,pt-PT,qu,rm,rn,ro,ru,rw,sd,sh,si,sk,sl,sn,so,sq,sr,sr-ME,st,su,sv,sw,ta,te,tg,th,ti,tk,tl,tn,to,tr,tt,tum,tw,ug,uk,ur,uz,vi,wo,xh,yi,yo,zh-CN,zh-TW,zu",
layout: window.google.translate.TranslateElement.InlineLayout.VERTICAL
},
googleTranslateRef.current
);
}
};
intervalId = setInterval(checkGoogleTranslate, 100);
return () => clearInterval(intervalId);
}, []);

return (
<div>
<div ref={googleTranslateRef}></div>
</div>
);
};

export default TranslateComponent;

This React component creates a translation widget using Google Translate. Here’s a simple breakdown:

Imports: It imports necessary modules from React.

Functional Component: Defines a functional component called TranslateComponent.

State Ref: It creates a reference (googleTranslateRef) using the useRef hook. This reference is used to attach the translation widget to a specific DOM element.

Effect Hook: Utilizes the useEffect hook to perform side effects when the component mounts. It sets up an interval to repeatedly check if Google Translate APIs are loaded.

Google Translate Check: The checkGoogleTranslate function verifies if the Google Translate APIs are available. Once confirmed, it clears the interval and initializes a new translation widget using the

new window.google.translate.TranslateElement constructor.

Cleanup: It clears the interval when the component unmounts to avoid memory leaks.

Render: The component renders a <div> which will serve as the container for the translation widget. The ref attribute is set to googleTranslateRef so that the widget can be attached to this DOM element.

In essence, this component sets up a translation widget from Google Translate, ensuring it’s initialized only when the necessary APIs are loaded, and cleans up after itself to prevent any memory leaks.

Create Layout for our Webapp

// Layout.js
import React from "react";
import Header from "./Header.jsx";

const Layout = ({ children }) => {
return (
<div>
<Header/>
<main>{children}</main>
</div>
);
};

export default Layout;

In Index.js file create routes and wrapped with Layout

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import App from './App.js';
import Home from './Home.jsx';
import About from './About.jsx';
import Layout from './Layout.js';

ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<Router>
<Layout>
<Routes>
<Route path="/" element={<App />} />
<Route path='/home' element={<Home/>}/>
<Route path="/about-us" element={<About />} />
</Routes>
</Layout>
</Router>
</React.StrictMode>
);

Then simply integrate Translate Component

import { Link } from "react-router-dom";
import TranslateComponent from "./Translate";

const Header = () => {
return (
<header>
<nav>
<ul style={{ display: "flex", gap: "10px" ,listStyle:"none"}}>
<li><Link to='/home'>Home</Link></li>
<li><Link to='/about-us'>AboutUs</Link></li>
<li><TranslateComponent/></li>
</ul>
</nav>
</header>
);
};

export default Header;

Start Project “npm run start”

Select language

Congratulations! 🎉 You’ve successfully created a multi-language translator using Google Translate in your React application. Now, your website can reach a broader audience, breaking language barriers and fostering connections worldwide. Keep building and exploring the endless possibilities of React development!

If you have any questions or issues with implementing this component, feel free to ask.

Note: If you aim to build a better web application with multi-language support, integrating i18next for React is a recommended approach. Here’s why:

Robust Internationalization (i18n) Support: i18next is a powerful internationalization library that provides comprehensive support for handling translations, pluralization, formatting, and other i18n-related tasks.

Flexible and Scalable: i18next offers a flexible and scalable solution for managing translations in your React application. It supports various file formats for translation files, including JSON, YAML, and PO.

Community Support: i18next has a thriving community and extensive documentation, making it easier for developers to learn and troubleshoot any issues they encounter during development.

React Integration: i18next provides a dedicated package for React integration (react-i18next), which seamlessly integrates i18n features into React components. This makes it straightforward to use translation resources within your React application.

Efficient Development: By using i18next, you can streamline the development process of multi-language applications, allowing you to focus on building features rather than reinventing the wheel for i18n support.

By adopting i18next for React, you can ensure a smoother development experience and deliver a more polished and inclusive web application to your users.

--

--