How to add google recaptcha in create react app?

Viewed 4585

I'm trying to get the recaptcha response so that I can pass along it via redux-form.
Have tried the 2 methods below...

Attempt 1:
Specifying callback in <head>.

index.html:

<script src='https://www.google.com/recaptcha/api.js?onload=callback&render=explicit'></script>

The problem here is that the callback is in global scope but I need to access it in React components.

Attempt 2:
Specifying callback in DOM.

Component: handleRecaptcha(resp)

handleRecaptcha(resp) {
  console.log(resp);
}

Component: render():

<div className="g-recaptcha" data-callback={this.handleRecaptcha.bind(this)}  data-sitekey="***"></div>

index.html:

<script src='https://www.google.com/recaptcha/api.js'></script>

I get the message ReCAPTCHA couldn't find user-provided function: function () { [native code] } after submitting the recaptcha. Probably a scope problem too.

I'm trying to avoid using another library, since I think this is a rather trivial problem.
Would anyone happen to have any idea how to go about it?

All I need is to get hold of the widget instance, and do grecaptcha.getResponse(widget) to get the response. API ref

2 Answers

You could also try Reaptcha.

It is a lot cleaner, more modern and has more of a React-way approach in handling the reCAPTCHA widget.

<Reaptcha 
  sitekey="YOUR_API_KEY" 
  onVerify={() => {
    // Do something
  }}
/>
Related