Add reCAPTCHA Google Captcha to React

Tiempo de lectura: 2 minutos

Today we’re going to learn how we can validate a form, including a reCAPTCHA to prevent spam attacks by BOTS.

The first thing we need to do is register our reCAPTCHA code on Google: https://www.google.com/recaptcha/about/

And click on v3 Admin Console

Click on the plus (+) button to create a new one, and in this case, we’ll choose V2 invisible:

Google has a technique to verify invisible captcha using mouse movements.

We add the domains where the reCAPTCHA will work.

Once registered, copy the key and paste it into a file named GoogleUtils.tsx

export const GoogleReCaptchaSiteKey = "fsadfasdcdsafretrefrewf"

*Put your key.

Now install the library we’ll use to generate this reCAPTCHA, react-google-recaptcha

npm install --save react-google-recaptcha

And if we’re using TypeScript, add

npm i --save-dev @types/react-google-recaptcha

Now create a component named Captcha.tsx

import React from 'react';
import ReCAPTCHA from "react-google-recaptcha";
import { GoogleReCaptchaSiteKey } from '@/util/BaseURL';

interface Props {
captchaRef: any;
onChange?: (token: string  null) => void;
}

function Captcha({ captchaRef, onChange }: Props) {
    return (
        <ReCAPTCHA
            sitekey={GoogleReCaptchaSiteKey}
            size="invisible"
            ref={captchaRef}
            onChange={onChange}
        />
    );
}

export default Captcha;

And call it like this:

  • Create the necessary methods to execute:
  const captchaRef = useRef<any>(null);
  const [tokenCaptcha, setTokenCaptcha] = useState<string  null>(null);

  //To login
  useEffect(() => {
     alert('TOKEN Captcha: ' + tokenCaptcha);
    //login();
  }, [tokenCaptcha])

  function checkCaptcha() {
    captchaRef.current.execute();
  }
  • Add the captcha to the form:
  <CaptchaRecaptcha captchaRef={captchaRef} onChange={(token) => { setTokenCaptcha(token) }} />

And in the button, add the checkCaptcha function instead of submitting the form:
<pre class=”EnlighterJSRAW” data-enlighter-language=”generic” data-enlighter-theme=”” data-enlighter-highlight=”” data-enlighter-linenumbers=”” data-enlighter-lineoffset=”” data-enlighter-title=”” data

Leave a Comment