javascriptcssreactjsinvisible-recaptcharecaptcha-v3

Showing google Recaptcha V3 floater only on specific Pages of React Application


i've react application with multiple # routes & google recaptcha v3,

i want to show recaptcha floater only on specific pages (# route) like login & forms.

How to achieve this.

Tried -

.grecaptcha-badge { 
    visibility: hidden;
}
#root #mainContainer .login:not(.empty) +  div>.grecaptcha-badge { 
    visibility: visible;
}

.grecaptcha-badge { 
    visibility: hidden;
}
#root #mainContainer .login ~ div>.grecaptcha-badge { 
    visibility: visible;
}

showing hiding by javascript > componentWillMount - > page's componentwillmount calls before the google recaptcha renders, so it dont get the element


Solution

  • Declare this outside your component:

    const toggleCaptchaBadge = (show: boolean) => {
      const badge = document.getElementsByClassName('grecaptcha-badge')[0];
      if (badge && badge instanceof HTMLElement) {
        badge.style.visibility = show ? 'visible' : 'hidden';
      }
    };
    

    Inside call this useEffect hook:

    useEffect(() => {
        toggleCaptchaBadge(true);
        return () => toggleCaptchaBadge(false);
      }, []);