react-google-recaptcha

repository·master·Indexed 22 days ago

https://github.com/dozoisch/react-google-recaptcha

A React component wrapper for Google reCAPTCHA v2 (version 3.1.0) that simplifies integration by handling script loading and providing a component-based API. Supports standard and invisible reCAPTCHA implementations, CSP nonce support, and programmatic execution via execute() and executeAsync() methods.

Tokens
2.6K
Snippets
11
Records
12
Agent score
78%

What's inside react-google-recaptcha

  1. Migrate from react-google-recaptcha v1.0 to v2.0

    master

    When upgrading from version 1.0 to 2.0, the following changes to the component options must be applied:

    1. Language Configuration: The options.lang property has been removed. To change the language of the reCAPTCHA widget, use the hl prop on the component instead.
    2. Unmounting Behavior: The options.removeOnUnmount property has been removed. This property is no longer necessary for language changes as language is now handled via the hl prop.
    // Instead of:
    // <ReCAPTCHA options={{ lang: 'fr' }} />
    
    // Use:
    <ReCAPTCHA hl='fr' />
  2. Hide the reCAPTCHA badge

    master

    You can hide the reCAPTCHA badge using CSS, but Google requires you to include specific branding text in your user flow to remain compliant.

    CSS to hide badge:

    .grecaptcha-badge { visibility: hidden; }

    Required branding text:

    This site is protected by reCAPTCHA and the Google
        <a href="https://policies.google.com/privacy">Privacy Policy</a> and
        <a href="https://policies.google.com/terms">Terms of Service</a> apply.
  3. Implement Invisible reCAPTCHA

    master

    To use an invisible reCAPTCHA, set the size prop to "invisible". You must then programmatically trigger the challenge using either the execute() method or the executeAsync() method.

    // Approach 1: Using execute() via ref
    import ReCAPTCHA from "react-google-recaptcha";
    
    const recaptchaRef = React.createRef();
    
    ReactDOM.render(
      <form onSubmit={() => { recaptchaRef.current.execute(); }}>
        <ReCAPTCHA
          ref={recaptchaRef}
          size="invisible"
          sitekey="Your client site key"
          onChange={onChange}
        />
      </form>,
      document.body
    );
    // Approach 2: Using executeAsync() with a promise-based approach
    import ReCAPTCHA from "react-google-recaptcha";
    
    const ReCAPTCHAForm = (props) => {
      const recaptchaRef = React.useRef();
    
      const onSubmitWithReCAPTCHA = async () => {
        const token = await recaptchaRef.current.executeAsync();
        // apply to form data
      }
    
      return (
        <form onSubmit={onSubmitWithReCAPTCHA}>
          <ReCAPTCHA
            ref={recaptchaRef}
            size="invisible"
            sitekey="Your client site key"
          />
        </form>
      )
    }
  4. Configure global reCAPTCHA options

    master

    You can configure global properties by setting window.recaptchaOptions. This is useful for using reCAPTCHA via recaptcha.net if google.com is blocked, or for enabling Google Enterprise reCAPTCHA.

    window.recaptchaOptions = {
      useRecaptchaNet: true,
      enterprise: true,
    };
  5. Basic usage of the ReCAPTCHA component

    master

    To use the default <ReCAPTCHA /> component, provide a sitekey (obtained from the Google reCAPTCHA admin console) and an onChange callback function. The component automatically loads the Google reCAPTCHA script asynchronously.

    import ReCAPTCHA from "react-google-recaptcha";
    
    function onChange(value) {
      console.log("Captcha value:", value);
    }
    
    ReactDOM.render(
      <ReCAPTCHA
        sitekey="Your client site key"
        onChange={onChange}
      />,
      document.body
    );
  6. ReCAPTCHA Component Instance API

    master

    You can access utility functions via a ref attached to the <ReCAPTCHA /> component instance:

    - `getValue()`: returns the value of the captcha field
    - `getWidgetId()`: returns the recaptcha widget Id
    - `reset()`: forces reset
    - `execute()`: programmatically invoke the challenge (required for `size="invisible"`)
    - `executeAsync()`: programmatically invoke the challenge and return a promise that resolves to the token or errors.
  7. Manually load the reCAPTCHA script

    master

    If you want to manage the grecaptcha dependency and script loading yourself, you can use the barebone <ReCAPTCHA /> component by passing the grecaptcha object directly.

    import { ReCAPTCHA } from "react-google-recaptcha";
    
    const grecaptchaObject = window.grecaptcha; // You must provide access to the google grecaptcha object.
    
    render(
      <ReCAPTCHA
        ref={(r) => this.recaptcha = r}
        sitekey="Your client site key"
        grecaptcha={grecaptchaObject}
      />,
      document.body
    );
  8. ReCAPTCHA Component Props

    master

    The <ReCAPTCHA /> component accepts the following props to customize its behavior and appearance:

    | Name | Type | Description |
    |:---- | ---- | ------ |
    | asyncScriptOnLoad | func | *optional* callback when the google recaptcha script has been loaded |
    | badge | enum | *optional* `bottomright`, `bottomleft` or `inline`. Positions reCAPTCHA badge. *Only for invisible reCAPTCHA* |
    | hl | string | *optional* set the hl parameter, which allows the captcha to be used from different languages |
    | isolated | bool | *optional* For plugin owners to not interfere with existing reCAPTCHA installations on a page. If true, this reCAPTCHA instance will be part of a separate ID space. *(__default:__ `false`)* |
    | onChange | func | The function to be called when the user successfully completes the captcha |
    | onErrored | func | *optional* callback when the challenge errored, most likely due to network issues. |
    | onExpired | func | *optional* callback when the challenge is expired and has to be redone by user. By default it will call the onChange with null to signify expired callback. |
    | sitekey | string | The API client key |
    | size | enum | *optional* `compact`, `normal` or `invisible`. This allows you to change the size or do an invisible captcha |
    | stoken | string | *optional* set the stoken parameter, which allows the captcha to be used from different domains |
    | tabindex | number | *optional* The tabindex on the element *(__default:__ `0`)* |
    | type | enum | *optional* `image` or `audio` The type of initial captcha *(__defaults:__ `image`)* |
    | theme | enum | *optional* `light` or `dark` The theme of the widget *(__defaults:__ `light`)* |
  9. Use the default RecaptchaWrapper component

    master

    The default export of this package is RecaptchaWrapper. Use this component to wrap your reCAPTCHA implementation, likely providing a higher-level abstraction or integration layer for the core ReCAPTCHA component.

    import RecaptchaWrapper from 'react-google-recaptcha';