I have integrated the Google Translate script into my React application to provide translation functionality. However, I’m encountering an intermittent issue where the translator dropdown doesn’t consistently load on every page visit. Sometimes it loads fine, but other times it requires a page reload to appear.
I have added the Google Translate script in the index.html file of the public folder and initialized it using a JavaScript function in the React component. Despite this setup, the translator seems to be inconsistently available.
I suspect there might be an issue with the asynchronous loading of the script or the initialization process. I’ve tried to ensure that the initialization function is called only after the Google Translate script has been fully loaded, but the problem persists.
I’m seeking advice on how to troubleshoot and resolve this issue to ensure that the Google Translate functionality is consistently available to users on all pages of my React app. See the blue type div on bottom right above community and support textgoogle translator loaded perfectly for translator in attached images linkstranslator not loaded here.
I tried to load it using the code in index.html and here is my code.
<script>
// Function to initialize Google Translate when the element is present
function initializeGoogleTranslate() {
if (document.getElementById('google_translate_element')) {
// Load the Google Translate script dynamically
var script = document.createElement('script');
script.src = 'https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit';
script.async = true;
googleTranslateElementInit();
// Append the script to the document head
document.head.appendChild(script);
}
}
// Callback function for Google Translate initialization
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element');
}
// Call the function to initialize Google Translate
initializeGoogleTranslate();
</script>
and here is the targeted div i added in App.js
<div id="google_translate_element" className=" d-flex justify-content-center align-items-center"></div>
2
Answers
Yeah, once upon a time Google translate worked like a charm but in the last couple of years it’s gone funny!
Here’s what I do… see the relevant comment below about how it was fixed.
NB: In the past I didn’t need to call the function at all… the parameter on the URL would kick-start the process automatically.
Well I’ve demonstrated how it can work… synchronously.
However, between you callbacks and other async declarations, I’m not surprised your version doesn’t work!
So… any chance of doing things synchronously or does it "have" to be like that in your environment?
I’ll leave you with that.