javascriptreactjsnext.jsgoogle-translate

Integrating google translate widget in Next JS application


I am trying to integrate google translate dropdown widget in my Next Js application, I integrated that the widget also but when I try to redirect from one page to another where the widget will not be available, the page gets blank and throws error like NotFoundError: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.

I tried to not clean up the component for persisting the script but it also doesn't seem to be working.

"use client";
  
import { useEffect } from "react";
  

  
const GoogleTranslate = () => {
  
  useEffect(() => {
  
    // Load the Google Translate script
  
    const script = document.createElement("script");
  
    script.src =
  
      "https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit";
  
    script.async = true;
  
    document.body.appendChild(script);
  

  
    // Initialize the Google Translate element
  
    window.googleTranslateElementInit = () => {
  
      new window.google.translate.TranslateElement(
  
        { pageLanguage: "en" },
  
        "google_translate_element"
  
      );
  
    };
  
  }, []);
  

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

export default GoogleTranslate;

This is my google translate component code and I am using it in the header of the application like this,

<AppBox>
<GoogleTranslate />
</AppBox>

Note: I am using App Router


Solution

  • After hours of debugging, I came across this comment in github, which solves my problem. I hope those who face this issue can also look into this comment, which will be helpful, thank you! https://github.com/facebook/react/issues/11538#issuecomment-390386520