npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-grecaptcha-v3

v0.4.5

Published

Google Recaptcha V3 for React.js based application. Keep website performance high while prioritizing security.

Downloads

228

Readme

Google Invisible ReCaptcha components for React based application

Keep website performance high while prioritizing security.

type definition npm package

Please read the documentation about Google reCAPTCHA on their official website before installation. Obtain a siteKey (your reCaptcha token) before using this library.

Key Features 🎯

  • Prevent degrading PageSpeed Insights score with power of injectionDelay property.
  • Lazy siteKey in case it is provided by back-end API.
  • Lazy load reCaptcha assets for key points of your application. Function provided by useSkipInjectionDelay hook allows to ignore injectionDelay
  • Clear versioning with help of Changeset.
  • Highly tested code with Typescript and Jest.
  • Confirmed Provenance by npm. It guarantees transparency in a library release process.

How to install?

  • yarn add react-grecaptcha-v3 for Yarn.
  • pnpm add react-grecaptcha-v3 for pnpm
  • npm install react-grecaptcha-v3 for npm

Components documentation

ReCaptchaProvider

react-grecaptcha-v3 provides a ReCaptchaProvider provider component that should be used to wrap around your components.

ReCaptchaProvider'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 unecessarily when your components re-rendered.

Same thing applied when you use this library with a 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.

Property types for ReCaptchaProvider

type Props = {
    siteKey: string | null;
    useRecaptchaNet?: boolean = false;
    enterprise?: boolean = false;
    scriptProps?: = {
        nonce?: string;
        defer?: boolean = true;
        async?: boolean = true;
        appendTo?: 'head' | 'body';
        id?: string = 'rusted_labs_react_recaptcha_v3';
    };
    injectionDelay?: number;
};

A short description for each property

| Property name | Description | | :---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | | siteKey | Your recaptcha key, get one from google recaptcha admin console. In case null provided events still will be recorded. Those events will be sent when siteKey provided. Also, google recaptcha script will not be loaded until siteKey provided. This can be helpful in case you want take control of this process. For example, to reduce impact of recaptcha on your pagespeed score . | | scriptProps | The injectedscript tag can be customized with this prop. It allows you to add async, defer, nonce attributes to the script tag. appendTo attribute controls whether the injected script will be added to the document body or head with . | | useRecaptchaNet | Load script fromrecaptcha.net instead of Google domain. This can help to workaround ad blockers. https://developers.google.com/recaptcha/docs/faq#can-i-use-recaptcha-globally | | enterprise | Load script for Enterprise. Get an Enterprise key before using it. Read more | | injectionDelay | In case you don't want to blow up yourPageInsights Score you can defer script loading by specifing threshold time. Events will be recorded and flushed at once on script load. Timeout should be specified in milliseconds. Plase note, that in case injectionDelay changed timeout is reseted. |

React Hook: useGoogleReCaptcha

There is only one way to call Google reCaptcha. Hook useExecuteReCaptcha.

The function returned by useGoogleReCaptcha returns promise with resolved reCaptcha token result. This token is used to validate protection score on your server-side and decide whether user is bot or not. Please note, in case your parent component tree not wrapped by ReCaptchaProvider a console error will be shown and event will be ignored.

Use the hook as provided in the following example.

import { ReCaptchaProvider, useExecuteReCaptcha } from 'react-grecaptcha-v3'

const GoogleReCaptchaValidatorComponent = () => {
    const executeRecaptcha = useExecuteReCaptcha()

    // Create an event handler so you can call the verification on button click event or form submit
    const handleReCaptchaVerify = useCallback(async () => {
        const token = await executeRecaptcha('userAction')
        // Do whatever you want with the token
    }, [executeRecaptcha])

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

    return <button onClick={handleReCaptchaVerify}>Verify recaptcha</button>
}

ReactDOM.render(
    <ReCaptchaProvider siteKey="[Your recaptcha key]">
        <GoogleReCaptchaValidatorComponent />
    </ReCaptchaProvider>,
    document.getElementById('app')
)

useSkipInjectionDelay

"I need my Google reCAPTCHA to be loaded now, regardless of the injectionDelay property. What should I do?"

There is a way to ignore the injectionDelay and load reCAPTCHA assets immediately. The useSkipInjectionDelay hook returns a callback that accomplishes this. See the following usage example.

import { ReCaptchaProvider, useExecuteReCaptcha } from 'react-grecaptcha-v3'

const GoogleReCaptchaValidatorComponent = () => {
    const forceRecaptchaLoad = useSkipInjectionDelay()

    // Create an event handler so you can call the verification on button click event or form submit
    const handleReCaptchaVerify = useCallback(async () => {
        forceRecaptchaLoad() //Load google recaptcha NOW!
        const token = await executeRecaptcha('someVeryImportantAction')
        // Do whatever you want with the token
    }, [executeRecaptcha])

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

    return <button onClick={handleReCaptchaVerify}>Verify recaptcha</button>
}

ReactDOM.render(
    <ReCaptchaProvider siteKey="[Your recaptcha key]">
        <GoogleReCaptchaValidatorComponent />
    </ReCaptchaProvider>,
    document.getElementById('app')
)

In our example, we have shown an important action that requires a token as fast as possible. However, keep in mind that for invisible reCAPTCHA, such a case can be suspicious, leading to a worse score. It is better to prepare reCAPTCHA at an earlier stage.

For example, you can call useSkipInjectionDelay with some action triggered by the user earlier, when you do not need a token immediately.