I am working with the react-google-recaptcha to implement the invisible ReCaptcha, passing a ref to the ReCAPTCHA component and executing this._reCaptchaRef.current.execute()
inside the componentDidMount. https://stackblitz.com/edit/react-invisbile-recaptcha showcases a form that makes use of the reCaptcha.
the onChange callback passed to the captcha component will set the value of the captcha into the state. The initial render the captcha value is set into the state and everything seems to work just fine, click on the submit button and the state value is printed onto the console.
After a few seconds, if we click on submit and look at the console, the value of the captcha is null. I tried to compare the value passed to onChange and if it was null I would invoke the
this._reCaptchaRef.current.execute()
but the issue raises when the value is null and we invoke the function but the first on submit
, the value of captcha is null and every click from it will have the value in the state until it becomes null.
how do I invoke the Recaptcha for the submit button and also be able to pass the value of the captcha to the callback function?
The general idea is that the recaptcha token is valid only for a period of time. This is so that the tokens are not easily guessable by other computer systems.
Instead of doing the captcha on mount, you are supposed to execute it onSubmit
only, hence the user would have filled the form when they see the captcha if at all.
handleSubmit(event) {
event.preventDefault();
this._reCaptchaRef.current.execute()
}
This would in turn trigger the onChange
handler (or the onError
handler) and you can submit the form from there.
But if you would like to somehow, keep it in componentDidMount
, you can choose to reset the captcha and execute it again.
redoCaptcha() {
this._reCaptchaRef.current.reset();
this._reCaptchaRef.current.execute();
}
render() {
...
<ReCAPTCHA
onExpired={this.redoCaptcha}
/>
}