Making site multi language support using google translate for React js

pra*_*kar 2 javascript google-translate reactjs

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);
}
Run Code Online (Sandbox Code Playgroud)

And return render element .

  render() {
    return (
      <div id="google_translate_element"></div>
    );
  }
Run Code Online (Sandbox Code Playgroud)

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

小智 5

将您的谷歌翻译脚本移至index.html项目的根目录。

但是,您应该将以下代码留在您想要的位置:

render() {
    return (
      <div id="google_translate_element"></div>
    );
  }
Run Code Online (Sandbox Code Playgroud)

轻松解决问题。

  • 这对我不起作用。2021年有什么解决方案吗? (2认同)