Google Translate Widget Has Problem with Loading

Viewed 336

I am trying to put a Google Translate Widget on the header of a create-react-app website. But the frustrating part is the widget is sometimes loading, sometimes not. It just doesn't display at all (more often in mobile) and after refreshing the page it shows up. Here is the code:

Script:

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

Element:

         <div
            className="col-lg-1 col-md-1 col-1 my-auto"
            id="language-container"
          >
            <img
              src="...svg"
              id="language-icon"
              className="my-auto me-2"
            />
            <span id="google_translate_element"></span>
          </div>

So, I couldn't find any solution yet. If you think you might have one, please share it. Thanks.

1 Answers

I have found the solution. If you are trying to add Google Translate Widget into your create-react-app, you shouldn't directly copy the script tag and paste it into index.html file. This may cause a problem. Instead create a component and paste this:

import React, { useState, useEffect } from 'react';

const GoogleTranslate = () => {
  const googleTranslateElementInit = () => {
    new window.google.translate.TranslateElement(
      {
        pageLanguage: 'en',
        layout: window.google.translate.TranslateElement.FloatPosition.TOP_LEFT
      },
      '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>;
};

export default GoogleTranslate;
 
Related