1

I've been working on websites since 2014 but I am brand new to Gatsby & React, which my employer knew when they hired me. I'm learning React as quickly as I can now but I've got a piece of code that I'm hoping the community can help me understand what's happening with - it would work fine except that there's another script running in the template that is creating a terrible UX by creating a blank new tab - this is the same whether I'm working in gatsby develop or gatsby serve.

The code is the following provided here on SO by @j-gunderson that is used to set up Google Translate within one of the template's components:

  const GoogleTranslate = () => {

    const googleTranslateElementInit = () => {
        new window.google.translate.TranslateElement({ pageLanguage: 'en', includedLanguages : 'es', layout: window.google.translate.TranslateElement.InlineLayout.SIMPLE }, '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>
      </>
    );
    
    } 

The issue that's happening seems to affect the elements within one of the divs created by Google's script

<a aria-haspopup="true" class="goog-te-menu-value" href="javascript:void(0)" target="_blank">
<span>Select Language</span>
<img src="https://www.google.com/images/cleardot.gif" alt="" width="1" height="1">
<span style="border-left: 1px solid rgb(187, 187, 187);">​</span>
<img src="https://www.google.com/images/cleardot.gif" alt="" width="1" height="1">
<span aria-hidden="true" style="color: rgb(155, 155, 155);">▼</span>
</a>

That target="_blank" doesn't exist until the menu is clicked on - the other script isn't anything that I have a task to work on & is interpreting the GT link as external & is applying target="_blank" to it & creating a nightmare situation. How can I target these elements & ensure that they maintain a target="_self" attribute on click or tap?

Jeff W
  • 147
  • 1
  • 2
  • 13

1 Answers1

0

I finally got this figured out! With a combination of this approach to target the classless spans inside the target div & this approach to preventDefault, the terrible UX experience no longer happens. The solution, which is wrapped inside the useEffect already posted, is:

        document.body.addEventListener( 'click', function ( event ) {
          if( document.querySelectorAll('div.goog-te-gadget-simple > span')) {
            event = event || window.event;
            event.preventDefault();
          };
        } );      
Jeff W
  • 147
  • 1
  • 2
  • 13