prabin badyakar
prabin badyakar

Reputation: 1736

Making site multi language support using google translate for React js

For simple html projects i can simple refer this link.

https://www.w3schools.com/howto/howto_google_translate.asp

But I'm trying to implement in react app . So I'm not able to replicate the code in react app.

componentDidMount() {
  googleTranslateElementInit(() => {
    new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element');
    });
    const script = document.createElement("script");
    script.src = "//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit";
    script.async = true;
    document.body.appendChild(script);
}

And return render element .

  render() {
    return (
      <div id="google_translate_element"></div>
    );
  }

This is showing me error saying google , googleTranslateElementInit is not defined.

How can I use google translator in react app ? Also is there any npm packages which can translate whole site ?

Thanks

Upvotes: 4

Views: 12355

Answers (6)

Noman Ghayyur
Noman Ghayyur

Reputation: 1

import { useEffect } from "react";

const App = () => {

  const googleTranslateElementInit = () => {
    new window.google.translate.TranslateElement(
      {
        pageLanguage: "en",
        layout: window.google.translate.TranslateElement.InlineLayout.SIMPLE,
        autoDisplay: false
      },
      "google_translate_element"
    );
  };

  useEffect(() => {
    var addScript = document.createElement("script");
    addScript.setAttribute(
      "src",
      "//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"
    );
    document.body.appendChild(addScript);
    window.googleTranslateElementInit = googleTranslateElementInit;
  }, []);

  return (
    <>
      <div id="google_translate_element"></div>
      <h4>Start building your app. Happy Coding!</h4>
    </>
  );
};

export default App;

just copy and past it into your App.jsx and you are good to go, Happy Coding!

Upvotes: 0

Late 2023 answer. If you want to use Google Translate on the fly in React, using the TranslateElement. It does matter where or when you add it to the project as long as you append the script and the element that Google needs. I made it with a custom hook:

function useGoogleTranslateScript() {
    useEffect(() => {
        const addScript = document.createElement('script');
        addScript.setAttribute(
            'src',
            '//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit'
        );
        document.body.appendChild(addScript);
        // debugger
        window.googleTranslateElementInit = () => {
            new window.google.translate.TranslateElement(
                {
                    pageLanguage: 'en',
                    includedLanguages: 'en,es',//here include all languages that you need
                },
                'google_translate_element'
            );
        };
    }, []);
}

You can place the hook where the translate component is gonna be. DONE MORE ADVANCE: You can hide all Google components, and handle the dropdown by yourself, make sure you change the cookie of googtrans to the chosen language in the dropdown: to set the cookies:

export const setCookie = (cName, cValue, exDays) => {
    let d = new Date(),
        expires = exDays;
    if (typeof exDays === 'number') {
        d.setTime(d.getTime() + (exDays * 24 * 60 * 60 * 1000));
        expires = "expires=" + d.toUTCString();
    }
    document.cookie = cName + "=" + cValue + ";" + expires + ";path=/";
}

to use it:

setCookie('googtrans', `/en/${value}`, 'Session')
//important
window.location.reload()

Don't forget to reload the location.

Upvotes: 2

Nate
Nate

Reputation: 535

For those in 2021 and hopefully a few more years before Google decides to change implementation method, this is how I resolved it.

Add the below script to your index.html file found in the public directory:

<script src="https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit" async></script>
<script type="text/javascript">
  function googleTranslateElementInit() {
    new google.translate.TranslateElement(
      {
        pageLanguage: "en",
        layout: window.google.translate.TranslateElement.InlineLayout.VERTICAL,
      }, 
      'google_translate_element'
    );
  }
</script>

Then, create a component, to be imported anywhere you want to use the translate plugin, with any name of your choice. I will use GoogleTranslate.jsx for this purpose of this answer.

In the newly created component, paste this code:

import React, { useEffect } from "react";

const GoogleTranslate = () => {
  useEffect(() => {
    // in some cases, the google translate script adds a style to the opening html tag.
    // this added style disables scrolling.
    // the next 3 lines removes this added style in order to re-enable scrolling.
    if (window.document.scrollingElement.hasAttribute("style")) {
      window.document.scrollingElement.setAttribute("style", "");
    }
  });

  return (
    <div id="google_translate_element"></div>
  );
};

export default GoogleTranslate;

Import the component wherever you want to use the translate plugin.

If this solution worked for you, kindly up vote so it can easily be shown to others searching. If it didn't, don't hesitate to drop a comment

Upvotes: 0

Pankaj Upadhyay
Pankaj Upadhyay

Reputation: 2138

Go to public folder > index.html

add code in body tag

<script type="text/javascript">
function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

create component

import React from 'react';
import './style.css';

const GoogleTranslate = (props) => {

    return(
        <div id="google_translate_element"></div>
    )
}

export default GoogleTranslate

import GoogleTranslate from './GoogleTranslate';

<GoogleTranslate />

Upvotes: -1

Jo&#227;o Furtado
Jo&#227;o Furtado

Reputation: 1

Change render to:

render() {
  return (
    <script type='text/javascript' src='//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit' />
    <div id="google_translate_element"></div>
  );
}

Create googleTranslateElementInit and use window.google instead of google:

googleTranslateElementInit () {
  /* eslint-disable no-new */
  new window.google.translate.TranslateElement({pageLanguage: 'pt', layout: window.google.translate.TranslateElement.FloatPosition.TOP_LEFT}, 'google_translate_element')
}

Change componentDidMount to:

componentDidMount () {
  window.googleTranslateElementInit = this.googleTranslateElementInit
}

Upvotes: 0

Abiodun Adisa
Abiodun Adisa

Reputation: 71

Move your google translate script to the root index.html of your project.

However, you should leave the below code at your desired location:

render() {
    return (
      <div id="google_translate_element"></div>
    );
  }

Fixes the problem easily.

Upvotes: 7

Related Questions