Giter VIP home page Giter VIP logo

reaptcha's Introduction

Reaptcha

Latest npm version Next npm version GitHub license TravisCI badge Coverage Status Greenkeeper badge Conventional Commits Commitizen friendly Minified package size Minified gzipped package size

A clean, modern and simple React wrapper for Google reCAPTCHA.

Why another library?

I've been using other React wrappers for reCAPTCHA like react-recaptcha or react-google-recaptcha but unfortunately both of them provide a non-react way (declaring the callbacks outside React components, not inside them) to handle all the reCAPTCHA callbacks which didn't feel clean and I didn't like this approach personally.

This is why I've decided to give it a try to create a cleaner approach and this is the result.

Features

  • All callbacks in your React component
  • Automatic reCAPTCHA script injection and cleanup
  • Usable with multiple reCAPTCHA instances
  • Full control over every reCAPTCHA instance
  • reCAPTCHA instance methods with promises and clean error messages
  • SSR ready

Installation

Just install the package with npm:

npm install --save reaptcha

or with yarn:

yarn add reaptcha

Usage

IMPORTANT NOTE: Reaptcha injects reCAPTCHA script into DOM automatically by default. If you are doing it manually, check out this description.

First of all, you'll need a reCAPTCHA API key. To find out how to get it - check this guide.

To see how Reaptcha actually works, visit the example page.

If you'd also like to see the code for the example, it is right here.

Default - Automatic render

By default Reaptcha injects the reCAPTCHA script into your head DOM element and renders a I'm a robot captcha.

Here's a quick example how can you use Reaptcha to verify your form submission:

import React, { Component } from 'react';
import Reaptcha from 'reaptcha';

class MyForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      verified: false
    };
  }

  onVerify = () => {
    this.setState({
      verified: true
    });
  };

  render() {
    return (
      <form>
        <Reaptcha sitekey="YOUR_API_KEY" onVerify={this.onVerify} />
        <button type="submit" disabled={!this.state.verified}>
          Submit
        </button>
      </form>
    );
  }
}

Explicit render

In order to render Reaptcha explicitly, you need to pass the explicit prop, store the reference to the instance and call the renderExplicitly function manually.

Caution! In order to prevent race-conditions, make sure you render the reCAPTCHA after the script successfuly loads. To do that, pass a function the the onLoad prop where you'll get informed that everything is ready to render.

Here's an example:

import React, { Fragment, Component } from 'react';
import Reaptcha from 'reaptcha';

class MyForm extends Component {
  constructor(props: Props) {
    super(props);
    this.captcha = null;
    this.state = {
      captchaReady: false
    };
  }

  onLoad = () => {
    this.setState({
      captchaReady: true
    });
  };

  onVerify = () => {
    // Do something
  };

  render() {
    return (
      <Fragment>
        <Reaptcha
          ref={e => (this.captcha = e)}
          sitekey="YOUR_API_KEY"
          onLoad={this.onLoad}
          onVerify={this.onVerify}
          explicit
        />
        <button
          onClick={() => {
            this.captcha.renderExplicitly();
          }}
          disabled={this.state.recaptchaReady}
        >
          Render reCAPTCHA
        </button>
      </Fragment>
    );
  }
}

Invisible

When you want to have an invisible reCAPTCHA, you'll have to execute it manually (as user won't have any possibility to do it). This can be done similarly to explicit rendering - saving the reference to the Reaptcha instance and call the execute method on it.

Additionally, invisible reCAPTCHA can be of course also rendered automatically or explicitly - this is your choice and the reference how to do it is right above.

import React, { Fragment, Component } from 'react';
import Reaptcha from 'reaptcha';

class MyForm extends Component {
  constructor(props: Props) {
    super(props);
    this.captcha = null;
  }

  onVerify = () => {
    // Do something
  };

  render() {
    return (
      <Fragment>
        <Reaptcha
          ref={e => (this.captcha = e)}
          sitekey="YOUR_API_KEY"
          onVerify={this.onVerify}
          size="invisible"
        />
        <button
          onClick={() => {
            this.captcha.execute();
          }}
        >
          Execute reCAPTCHA
        </button>
      </Fragment>
    );
  }
}

Reset

You can also manually reset your reCAPTCHA instance. It's similar to executing it:

<Fragment>
  <Reaptcha
    ref={e => (this.captcha = e)}
    sitekey="YOUR_API_KEY"
    onVerify={() => {
      // Do something
    }}
  />
  <button onClick={() => this.captcha.reset()}>Reset</button>
</Fragment>

Instance methods

It's known that calling methods of a React component class is a really bad practice, but as we're doing something uncommon to typical React components - it's the only method that popped in that actually is intuitive and React-ish.

So to get access to the methods, just save the reference to the component instance:

<Reaptcha ref={e => (this.captcha = e)} />

If you have an idea how to do this better, feel free to file an issue to discuss it!

Available and usable Reaptcha instance methods:

Name Returns Description
renderExplicitly Promise<void> Renders the reCAPTCHA instance explicitly
reset Promise<void> Resets the reCAPTCHA instance
execute Promise<void> Executes the reCAPTCHA instance

Customisation

Reaptcha allows to customize your reCAPTCHA instances with any available properties documented in the reCAPTCHA docs for all of the types:

Name Required Type Default Description
id no string - Id for the container element
className no string 'g-recaptcha' Classname for the container element
sitekey yes string - Your reCAPTCHA API key
theme no 'light' | 'dark' 'light' reCAPTCHA color theme
size no 'compact' | 'normal' | 'invisible' 'normal' reCAPTCHA size
badge no 'bottomright' | 'bottomleft' | 'inline' 'bottomright' Position of the reCAPTCHA badge
tabindex no number 0 Tabindex of the challenge
explicit no boolean false Allows to explicitly render reCAPTCHA
inject no boolean true Handle reCAPTCHA script DOM injection automatically
isolated no boolean false For plugin owners to not interfere with existing reCAPTCHA installations on a page
hl no string - Language code for reCAPTCHA
onLoad no Function - Callback function executed when the reCAPTCHA script sucessfully loads
onRender no Function - Callback function executed when the reCAPTCHA successfuly renders
onVerify yes Function - Callback function executed on user's captcha verification. Returns user response token
onExpire no Function - Callback function executed when the reCAPTCHA response expires and the user needs to re-verify
onError no Function - Callback function executed when reCAPTCHA fails with an error

Caveats

Size-specific props

There are props that are size-specific and some of the props are not available for all of the sizes. Although if you will pass these props nothing bad will happen, they will just be ignored.

The size-exclusive props are:

  • I'm a robot: theme
  • Invisible: badge, isolated

Attaching reCAPTCHA script manually

If you want to attach the reCAPTCHA script manually to the DOM, simply pass the inject prop as false, like this:

<Reaptcha {...props} inject={false} />

This way Reaptcha won't inject the scripts by itself and won't break because of multiple reCAPTCHA scripts attached.

reaptcha's People

Contributors

greenkeeper[bot] avatar greenkeeperio-bot avatar jsardev avatar zhuangya avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.