November 24, 2023
O. Wolfson
In this tutorial, we'll learn how to integrate Google reCAPTCHA into a React form to enhance security and prevent automated submissions. We'll base our example on a simple contact form that includes an email field, a message field, and the reCAPTCHA widget.
Visit Google reCAPTCHA Site: Go to the Google reCAPTCHA website.
Sign In: Use your Google account to sign in.
Register a New Site:
Obtain Site Key and Secret Key: After registration, you’ll receive a Site Key and a Secret Key. Note these down as you’ll need them later.
In your React application, create a simple form component. Below is the code for a basic contact form:
jsximport React, { useState } from "react";
import ReCAPTCHA from "react-google-recaptcha";
export default function SimpleContactForm() {
const [email, setEmail] = useState("");
const [message, setMessage] = useState("");
const [isRecaptchaVerified, setIsRecaptchaVerified] = useState(false);
const handleRecaptchaChange = (value) => {
setIsRecaptchaVerified(!!value);
};
const handleSubmit = (event) => {
event.preventDefault();
if (!isRecaptchaVerified) {
alert("Please verify that you are not a robot.");
return;
}
// Here you will handle form submission, e.g., sending data to your server
console.log("Form Submitted", { email, message });
alert("Form submitted successfully!");
// Reset form and reCAPTCHA state
setEmail("");
setMessage("");
setIsRecaptchaVerified(false);
};
return (
<form onSubmit={handleSubmit}>
<div>
<label>Email:</label>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div>
<label>Message:</label>
<textarea
value={message}
onChange={(e) => setMessage(e.target.value)}
/>
</div>
<div>
<ReCAPTCHA
sitekey="YOUR_RECAPTCHA_SITE_KEY"
onChange={handleRecaptchaChange}
/>
</div>
<button type="submit">Submit</button>
</form>
);
}
Install reCAPTCHA Library: If you haven't already, install the react-google-recaptcha
library:
bashnpm install react-google-recaptcha
# or
yarn add react-google-recaptcha
Add reCAPTCHA to Your Form:
ReCAPTCHA
from the library.handleRecaptchaChange
) to update the state when the user completes the reCAPTCHA challenge.handleSubmit
function, check if reCAPTCHA has been verified before processing the form.Integrating Google reCAPTCHA in a React form is straightforward and enhances your application's security. Remember to handle the server-side verification of the reCAPTCHA response to ensure the form's integrity. This tutorial gives you a basic framework, which you can expand based on your specific requirements.