javascriptreactjsasynchronousrecaptchareact-google-recaptcha

How do I make code wait for ReCaptcha to render


I am trying to edit an attribute of an element created by reCaptcha. But to do so, I need to catch the iframe, that is being created. The problem is, when I use useEffect (Instead of ComponentDidMount/Update. The code runs too early. How can I make my code wait for the Captcha to render?

import ReCAPTCHA from 'react-google-recaptcha';
...
const ReCaptcha = ({ isRtl = true, onSuccess }) => {
  useEffect(() => {
    let direction;
    if (isRtl) {
      direction = 'rtl';
    } else {
      direction = 'ltr';
    }
    //This doesn't exist yet.
    const element = document.querySelector('iframe').contentDocument.getElementById('recaptcha-anchor-label');
    console.log(element);
    console.log(1);
    if (element) {
      element.setAttribute('dir', direction);
    }
  });

  const handleChange = value => {
    if (value) {
      onSuccess();
    }
  };
  console.log(2);
  return (
    <ReCAPTCHA
      sitekey={'6LdfLysUAAAAAIVunEmrVZGErd_74d1r7deXdksg'}
      onChange={handleChange}
    />
  );
};

Obviously I could add like a setTimeout, but that is a horrible practice.

I want to edit an attribute of the label, returned by ReCAPTCHA. I am using this package: https://www.npmjs.com/package/react-google-recaptcha

This component renders something like this:

<iframe>
  <html>
    <label id={'myLabel'} dir={'ltr'}>some label</label>
  </html>
</iframe>

And I want to change the dir attribute of #myLabel to rtl (dir is our internal attribute).


Solution

  • Ok I solved my issue by doing:

    <ReCAPTCHA
      hl={'ar'}
      sitekey={ReCaptchaKeys.siteKey}
      onChange={handleChange}
    />
    

    hl is a language code. References:

    https://developers.google.com/recaptcha/docs/language

    Setting reCAPTCHA Version 2 set another language other than English