salesforce npm react recaptcha code example

Example 1: react recaptcha signup form

import {
  GoogleReCaptchaProvider,
  useGoogleReCaptcha
} from 'react-google-recaptcha-v3';
import { Button } from '@chakra-ui/core';
import React from 'react';

const CaptchaButton = ({ onVerifyCaptcha }) => {
  const { executeRecaptcha } = useGoogleReCaptcha();
  const clickHandler = async () => {
    if (!executeRecaptcha) {
      return;
    }

    const token = await executeRecaptcha('contact');

    onVerifyCaptcha(token);
  };

  return (
    <Button onClick={clickHandler}>
      Please validate you are a human.
    </Button>
  );
};

export const ReCaptcha = ({ onVerifyCaptcha }) => (
  <GoogleReCaptchaProvider
    reCaptchaKey="<YOUR_KEY>"
  >
    <CaptchaButton onVerifyCaptcha={onVerifyCaptcha} />
  </GoogleReCaptchaProvider>
);

Example 2: react recaptcha signup form

import { ReCaptcha, StringInput, Textarea } from '@forms/base';
import React, { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';

export const ContactForm = () => {
  const { handleSubmit, errors, formState, register, setValue } = useForm({
    mode: 'onChange'
  });
  const [isSubmitting, setIsSubmitting] = useState(false);

  const onSubmit = (values) => {
    setIsSubmitting(true);
    console.log(values);

    setIsSubmitting(false);
  };

  const onVerifyCaptcha = (token) => {
    setValue('captchaToken', token);
  };

  useEffect(() => {
    register({ name: 'captchaToken' }, { required: true });
  });

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <ReCaptcha onVerifyCaptcha={onVerifyCaptcha} />
      <button
        isLoading={isSubmitting}
        type="submit"
      >
        Send Message
      </button>
    </form>
  );
};