2024-09-09 web, development, javascript

Setting Up Google reCAPTCHA in a React Form

By 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.

Step 1: Register Your Site with Google reCAPTCHA

  1. Visit Google reCAPTCHA Site: Go to the Google reCAPTCHA website.

  2. Sign In: Use your Google account to sign in.

  3. Register a New Site:

    • Click on the “+” icon or “Register a new site” button.
    • Choose the reCAPTCHA version (e.g., reCAPTCHA v2 or v3). For this tutorial, we'll use reCAPTCHA v2.
    • Enter your domain name(s) in the ‘Domains’ section.
    • Accept the terms of service and submit.
  4. 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.

Step 2: Set Up the React Form

In your React application, create a simple form component. Below is the code for a basic contact form:

jsx
import 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>
  );
}

Step 3: Integrate reCAPTCHA in Your Form

  1. Install reCAPTCHA Library: If you haven't already, install the react-google-recaptcha library:

    bash
    npm install react-google-recaptcha
    # or
    yarn add react-google-recaptcha
    
  2. Add reCAPTCHA to Your Form:

    • Import ReCAPTCHA from the library.
    • Use the Site Key you got from Google reCAPTCHA to initialize the widget.
    • Implement a change handler (handleRecaptchaChange) to update the state when the user completes the reCAPTCHA challenge.

Step 4: Handling Form Submission

  • In the handleSubmit function, check if reCAPTCHA has been verified before processing the form.
  • You might want to send the form data along with the reCAPTCHA response token to your backend server for verification (not covered in this tutorial but crucial for security).

Conclusion

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.