From 8b97fcb73eecac42916ba7b8cd45ab89daa1537a Mon Sep 17 00:00:00 2001 From: oonyeje Date: Wed, 29 Nov 2023 09:35:12 -0500 Subject: [PATCH] - add recaptcha boilerplate for contact form - still need to add api key to both project and ci/cd --- components/form/ContactForm/index.tsx | 47 ++++++++++++++--- package.json | 2 + pages/api/contact.ts | 72 +++++++++++++++++++-------- yarn.lock | 34 ++++++++++++- 4 files changed, 127 insertions(+), 28 deletions(-) diff --git a/components/form/ContactForm/index.tsx b/components/form/ContactForm/index.tsx index 56b2a24..3fd7f1b 100644 --- a/components/form/ContactForm/index.tsx +++ b/components/form/ContactForm/index.tsx @@ -1,31 +1,49 @@ -import { useState } from 'react'; +import { RefObject, useRef, useState } from 'react'; import { useForm, SubmitHandler, FieldValues } from 'react-hook-form'; +import ReCAPTCHA from 'react-google-recaptcha'; + +export interface ContactFormData extends FieldValues { + firstName: string, + lastName: string, + email: string, + subject: string, + summary: string, + honeypot_xyz: string +}; const ContactForm = () => { const { register, + resetField, handleSubmit, + setValue, formState: { errors }, } = useForm(); const [submitted, setSubmitted] = useState(false); - const handleFormSubmission: SubmitHandler = async (data) => { - console.log(data) + const handleFormSubmission: SubmitHandler = async (data: FieldValues) => { + const submissionData = data as ContactFormData; + console.log(submissionData) - const res = await fetch('/api/contact', { + if (submissionData.honeypot_xyz !== "") { + // Form submission is spam + return; + } + const res = await fetch('/api/contact', { method: 'POST', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json' }, - body: JSON.stringify(data) + body: JSON.stringify(submissionData) }); console.log('Response received') if (res.status === 200) { console.log('Response succeeded!') setSubmitted(true) + resetField('captchaToken') } }; @@ -33,6 +51,12 @@ const ContactForm = () => { console.log(error) }; + const onCaptchaChange = (token: string | null) => { + // Set the captcha token when the user completes the reCAPTCHA + if (token) { + setValue('captchaToken', token); + } + }; return (
@@ -62,11 +86,22 @@ const ContactForm = () => { {errors.subject &&

Subject is required.

}
+
+ +
+