appleboy / react-recaptcha

A react.js reCAPTCHA for Google
https://www.google.com/recaptcha/intro/index.html
BSD 3-Clause "New" or "Revised" License
635 stars 97 forks source link

Add execute function to provide support for invisible reCaptchas #187

Closed ericj17 closed 7 years ago

ericj17 commented 7 years ago

Adding an explicit execute function in the same fashion as the reset function so that a widgetId can be maintained. This will support the use of invisible reCaptcha as invisible reCaptchas requires calling grecaptcha.execute(widgetId)

I didn't get a chance to integrate an invisible recaptcha example with the existing example (doesn't seem to like having an invisible version together with an compact/normal version of the recaptcha on the same page). Below is an example for the invisible recaptcha on its own.

import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import Recaptcha from '../src';

// site key
const sitekey = 'xxxxxxx';

// specifying your onload callback function
const callback = () => {
  console.log('Done!!!!');
};

const verifyCallback = (response) => {
  console.log(response);
};

const expiredCallback = () => {
  console.log(`Recaptcha expired`);
};

// define a variable to store the invisible recaptcha instance
let invisibleRecaptchaInstance;

// handle reset of invisible recaptcha
const resetInvisibleRecaptcha = () => {
  invisibleRecaptchaInstance.reset();
};

// handle execution of invisible recaptcha
const executeInvisibleRecaptcha = () => {
  invisibleRecaptchaInstance.execute();
};

class App extends React.Component {
  render() {
    return (
      <div>
        <h1>Google Invisible Recaptcha</h1>
        <Recaptcha
          ref={e => invisibleRecaptchaInstance = e}
          sitekey={sitekey}
          size="invisible"
          render="explicit"
          verifyCallback={verifyCallback}
          onloadCallback={callback}
          expiredCallback={expiredCallback}
        />

        <button
          onClick={executeInvisibleRecaptcha}
        >
          Execute invisible recaptcha
        </button>
        <br/>
        <button
          onClick={resetInvisibleRecaptcha}
        >
          Reset invisible recaptcha
        </button>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('app'));