1.0.3 • Published 2 months ago

@google-recaptcha/react v1.0.3

Weekly downloads
-
License
MIT
Repository
github
Last release
2 months ago

🔑 React Google ReCaptcha

tool that easily and quickly add Google ReCaptcha for your website or application

Install

Install with npm or yarn

$ npm i @google-recaptcha/react
# or
$ yarn add @google-recaptcha/react

🦉 Philosophy

🔑 React Google ReCaptcha this is a library that will allow you to easily and quickly add Google ReCaptcha for your website or application. The main difference from other libraries is that all current versions of Google ReCaptcha are supported here.

Features

  • Support all recaptcha versions - support v3, v2-checkbox, v2-invisible
  • Enterprise mode - support enterprise
  • TypeScript support out of the box - full typed package
  • SSR - package work with server side render

Usage

Install 🔑 React Google ReCaptcha with npm or yarn

$ npm i @google-recaptcha/react
# or
$ yarn add @google-recaptcha/react

V3

Google ReCaptcha v3 returns a score for each request without user friction. The score is based on interactions with your site and enables you to take an appropriate action for your site.

import { GoogleReCaptchaProvider } from '@google-recaptcha/react';

const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
root.render(
  <GoogleReCaptchaProvider
    type="v3"
    siteKey="Your recaptcha sitekey"
  >
    <App />
  </GoogleReCaptchaProvider>
);

V2 invisible

Google ReCaptcha v2 invisible does not require users to solve any puzzles or enter any codes. Instead, it runs in the background and analyzes user behavior on the web page to determine if they are genuine users or potential bots.

import { GoogleReCaptchaProvider } from '@google-recaptcha/react';

const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
root.render(
  <GoogleReCaptchaProvider
    type="v2-invisible"
    siteKey="Your recaptcha key"
  >
    <App />
  </GoogleReCaptchaProvider>
);

V2 checkbox

When a user interacts with the Google ReCaptcha v2 checkbox, advanced algorithms analyze their behavior to distinguish between humans and bots. If the system suspects suspicious activity, additional challenges may be presented, such as image selections or puzzle-solving tasks.

import { GoogleReCaptchaProvider, GoogleReCaptchaCheckbox } from '@google-recaptcha/react';

const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
root.render(
  <GoogleReCaptchaProvider
    type="v2-checkbox"
    siteKey="Your recaptcha key"
  >
    <GoogleReCaptchaCheckbox
      onChange={(token) => {
        console.log(token);
      }}
    />
  </GoogleReCaptchaProvider>
);

Checkbox component

PropsTypeDefaultRequired?Note
idStringNoId of component
actionStringNoAn action name is used to describe user-initiated events. More info
classNameStringNoStyles for component
containerString or HTMLElementNoContainer ID where the recaptcha badge will be rendered
callback(token: string) => voidNoThe name of your callback function, executed when the user submits a successful response. The g-recaptcha-response token is passed to your callback.
errorCallback() => voidNoThe name of your callback function, executed when reCAPTCHA encounters an error (usually network connectivity) and cannot continue until connectivity is restored. If you specify a function here, you are responsible for informing the user that they should retry.
expiredCallback() => voidNoThe name of your callback function, executed when the reCAPTCHA response expires and the user needs to re-verify.
languageStringNooptional prop to support different languages that is supported by Google Recaptcha. See
themedark or lightlightNoThe color theme of the widget.
sizecompact or normalnormalNoThe size of the widget.
onChange(token: string) => voidNoWhen called with string (token), it means token retrieved. When called with false as an argument, it means the response expired and the user needs to re-verify. When called with Error, it means an error occurred and the widget cannot continue (usually network disconnection)

Enterprise

Google ReCaptcha Enterprise is built on the existing reCAPTCHA API and it uses advanced risk analysis techniques to distinguish between humans and bots. In order to enable enterprise mode, you need to set the flag isEnterprise in GoogleReCaptchaProvider. Also in this mode you can pass specials actions.

Examples

v2 checkbox

import { GoogleReCaptchaProvider, GoogleReCaptchaCheckbox } from '@google-recaptcha/react';

const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
root.render(
  <GoogleReCaptchaProvider
    type="v2-checkbox"
    siteKey="Your recaptcha key"
    isEnterprise
  >
    <GoogleReCaptchaCheckbox
      action="Your action name"
      onChange={(token: string) => {
          console.log(token);
      }}
    />
  </GoogleReCaptchaProvider>
);

v3 or v2 invisible

import { GoogleReCaptchaProvider } from '@google-recaptcha/react';

const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
root.render(
  <GoogleReCaptchaProvider
    type="Your type of recaptcha"
    siteKey="Your recaptcha key"
    isEnterprise
  >
    <App />
  </GoogleReCaptchaProvider>
);

API

GoogleReCaptchaProvider

@google-recaptcha/react provides a GoogleReCaptchaProvider provider component that should be used to wrap around your components.

GoogleReCaptchaProvider's responsibility is to load the necessary reCaptcha script and provide access to reCaptcha to the rest of your application.

Usually, your application only needs one provider. You should place it as high as possible in your React tree. It's to make sure you only have one instance of Google Recaptcha per page, and it doesn't reload unnecessarily when your components re-rendered.

Same thing applied when you use this library with framework such as Next.js or React Router and only want to include the script on a single page. Try to make sure you only have one instance of the provider on a React tree and to place it as high (on the tree) as possible.

GoogleReCaptchaProvider for v3 and v2-invisible

All the props that can be passed in provider for v2-invisible and v3:

PropsTypeDefaultRequiredNote
typev3 or v2-invisibleYesYour recaptcha version
siteKeyStringYesYour recaptcha key, get one from here
languageStringNoOptional prop to support different languages that is supported by Google Recaptcha
isEnterpriseBooleanNoWhen you enable to use the enterprise version, you must create new keys. These keys will replace any Site Keys you created in reCAPTCHA. Check the migration guide.
onLoad() => voidNoCallback function to load reCAPTCHA
onError() => voidNoCallback function to error reCAPTCHA
hostrecaptcha.net or google.comNoLoad script from recaptcha.net or google.com
scriptPropsObjectNoAll props used by <script> tag
explicit.containerString or HTMLElementNoContainer ID where the recaptcha badge will be rendered
explicit.tabIndexNumber0NoThe tabindex of the widget and challenge. If other elements in your page use tabindex, it should be set to make user navigation easier.
explicit.inheritBooleanNoUse existing data-* attributes on the element if the corresponding parameter is not specified. The parameters will take precedence over the attributes.
explicit.callback(token: string) => voidNoThe name of your callback function, executed when the user submits a successful response. The g-recaptcha-response token is passed to your callback.
explicit.errorCallback() => voidNoThe name of your callback function, executed when reCAPTCHA encounters an error (usually network connectivity) and cannot continue until connectivity is restored. If you specify a function here, you are responsible for informing the user that they should retry.
explicit.expiredCallback() => voidNoThe name of your callback function, executed when the reCAPTCHA response expires and the user needs to re-verify.
explicit.badgeinline or bottomleft or bottomright or hiddenbottomrightNoReposition the reCAPTCHA badge.

GoogleReCaptchaProvider for v2-checkbox

All the props that can be passed in provider for v2-checkbox. We also recommend using the checkbox component rather than explicitly loading the recaptcha checkbox.

PropsTypeDefaultRequiredNote
typev2-checkboxYesYour recaptcha version
siteKeyStringYesYour recaptcha key, get one from here
languageStringNoOptional prop to support different languages that is supported by Google Recaptcha
isEnterpriseBooleanNoWhen you enable to use the enterprise version, you must create new keys. These keys will replace any Site Keys you created in reCAPTCHA. Check the migration guide.
onLoad() => voidNoCallback function to load reCAPTCHA
onError() => voidNoCallback function to error reCAPTCHA
hostrecaptcha.net or google.comgoogle.comNoLoad script from recaptcha.net or google.com
scriptPropsObjectNoAll props used by <script> tag
explicit.containerString or HTMLElementNoContainer ID where the recaptcha badge will be rendered
explicit.tabIndexNumber0NoThe tabindex of the widget and challenge. If other elements in your page use tabindex, it should be set to make user navigation easier.
explicit.inheritBooleanNoUse existing data-* attributes on the element if the corresponding parameter is not specified. The parameters will take precedence over the attributes.
explicit.callback() => voidNoThe name of your callback function, executed when the user submits a successful response. The g-recaptcha-response token is passed to your callback.
explicit.errorCallback() => voidNoThe name of your callback function, executed when reCAPTCHA encounters an error (usually network connectivity) and cannot continue until connectivity is restored. If you specify a function here, you are responsible for informing the user that they should retry.
explicit.expiredCallback() => voidNoThe name of your callback function, executed when the reCAPTCHA response expires and the user needs to re-verify.
explicit.actionStringNoAn action name is used to describe user-initiated events corresponding
explicit.themedark or lightlightNoThe color theme of the widget. Depends on type of reCaptcha
explicit.sizecompact or normalnormalNoThe size of the widget. Depends on type of reCaptcha

Checkbox component

PropsTypeDefaultRequired?Note
idStringNoId of component
actionStringNoAn action name is used to describe user-initiated events. More info
classNameStringNoStyles for component
containerString or HTMLElementNoContainer ID where the recaptcha badge will be rendered
callback() => voidNoThe name of your callback function, executed when the user submits a successful response. The g-recaptcha-response token is passed to your callback.
errorCallback() => voidNoThe name of your callback function, executed when reCAPTCHA encounters an error (usually network connectivity) and cannot continue until connectivity is restored. If you specify a function here, you are responsible for informing the user that they should retry.
expiredCallback() => voidNoThe name of your callback function, executed when the reCAPTCHA response expires and the user needs to re-verify.
languageStringNooptional prop to support different languages that is supported by Google Recaptcha. See
themedark or lightlightNoThe color theme of the widget.
sizecompact or normalnormalNoThe size of the widget.
onChange(token: string) => voidNoWhen called with string (token), it means token retrieved. When called with false as an argument, it means the response expired and the user needs to re-verify. When called with Error, it means an error occurred and the widget cannot continue (usually network disconnection)

useGoogleReCaptcha hook

If you prefer a React Hook approach, you can choose to use the custom hook useGoogleReCaptcha. We recommend using this hook for v2 invisible and v3 to trigger recaptcha execution.

The executeV3 and executeV2Invisible function returned from the hook can be undefined when the recaptcha script has not been successfully loaded.

import { GoogleReCaptchaProvider, useGoogleReCaptcha } from '@google-recaptcha/react';

const App = () => {
  const { executeV3 } = useGoogleReCaptcha();

  // Create an event handler so you can call the verification on button click event or form submit
  const handleReCaptchaVerify = useCallback(async () => {
    if (!executeV3) {
      console.log('Execute recaptcha not available');
      return;
    }

    const token = await executeV3();
  }, [executeV3]);

  // You can use useEffect to trigger the verification as soon as the component being loaded
  useEffect(() => {
    handleReCaptchaVerify();
  }, [handleReCaptchaVerify]);

  return <button onClick={handleReCaptchaVerify}>verify</button>;
};

const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
root.render(
  <GoogleReCaptchaProvider siteKey="Your recaptcha key">
    <App />
  </GoogleReCaptchaProvider>
);

withGoogleReCaptcha HOC

withGoogleReCaptcha is a HOC (higher order component) that can be used to integrate reCaptcha validation with your component and trigger the validation programmatically. It injects the wrapped component with googleReCaptcha object.

The object contains the executeV3 and executeV2Invisible function that can be called to validate the user action.

You are recommended to use the custom hook useGoogleReCaptcha over the HOC whenever you can. The HOC can be removed in future version.

import {
  GoogleReCaptchaProvider,
  withGoogleReCaptcha,
  WithGoogleReCaptchaParams
} from '@google-recaptcha/react';

const App = (props) => {
    // Create an event handler so you can call the verification on button click event or form submit
    const handleReCaptchaVerify = useCallback(async () => {
        if (!props.executeV3) {
            console.log('Execute recaptcha not available');
            return;
        }

        const token = await props.executeV3();
    }, [props.executeV3]);

    // You can use useEffect to trigger the verification as soon as the component being loaded
    useEffect(() => {
        handleReCaptchaVerify();
    }, [handleReCaptchaVerify]);

    return <button onClick={handleReCaptchaVerify}>verify</button>;
};

export const WithGoogleRecaptchaApp = withGoogleReCaptcha(App);

const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
root.render(
  <GoogleReCaptchaProvider siteKey="Your recaptcha key">
    <WithGoogleRecaptchaApp />
  </GoogleReCaptchaProvider>
);

generateGoogleReCaptchaScriptSrc

The function generateGoogleReCaptchaScriptSrc function may be needed for applications with ssr to get a link for the recaptcha script and load it before rendering the UI.

ParametersTypeRequiredNote
hostrecaptcha.net or google.comNoLoad script from recaptcha.net or google.com
isEnterpriseBooleanYes
renderStringYessiteKey of reCaptcha
hlStringNoProp to support different languages that is supported by Google Recaptcha
badgeinline or bottomleft or bottomrightNoReposition the reCAPTCHA badge. Depends on type of reCaptcha. If not provide badge is hidden

generateGoogleReCaptchaHiddenBadgeStyles

The function generateGoogleReCaptchaHiddenBadgeStyles function returns hidden styles for Google ReCaptcha badge.

✨ Contributors