formspree / formspree-js

The fastest way to hook up a React form
https://formspree.io/javascript
MIT License
63 stars 12 forks source link

Add recaptcha support #8

Closed colevscode closed 2 years ago

colevscode commented 2 years ago

Supports sending a function that resolves to a recaptcha response code to the data attribute of useForm. Example:

import * as React from "react";
import { useForm, ValidationError } from "@formspree/react";
import { useGoogleReCaptcha } from "react-google-recaptcha-v3";

export default function ContactForm() {
  const { executeRecaptcha } = useGoogleReCaptcha();

  const [state, handleSubmit] = useForm(process.env.NEXT_PUBLIC_FORM, {
    data: { "g-recaptcha-reponse": executeRecaptcha }
  });

  if (state.succeeded) {
    return <p>Thanks for your submission!</p>;
  }
  return (
    <form onSubmit={handleSubmit}>
      // ...    
    </form>
  );
}

Note that we don't correctly return a well formed validation error message from Formspree when the recaptcha response fails. We should respond with an appropriate errors property including code and message so that formspree-react and other clients can easily parse and display errors. (Though generally a recaptcha error message would indicate the form isn't set up correctly, and there's not much the submitter can do to fix it)