Skip to content

Instantly share code, notes, and snippets.

@heridev
Last active November 21, 2024 14:56
Show Gist options
  • Save heridev/df45e542e8b494677da2cd2dd56bd6dc to your computer and use it in GitHub Desktop.
Save heridev/df45e542e8b494677da2cd2dd56bd6dc to your computer and use it in GitHub Desktop.
Recaptcha from google with React, how to implement it if needed in your contact form page
  1. install
npm install react-google-recaptcha
  1. how it looks
import ReCAPTCHA from 'react-google-recaptcha';
import { useRef } from 'react';

function ContactForm() {
  const captchaRef = useRef(null);

  const formik = useFormik({
    initialValues: {
      message: '',
      captcha: ''
    },
    validationSchema: Yup.object({
      message: Yup.string().required('Required'),
      captcha: Yup.string().required('Please complete the captcha')
    }),
    onSubmit: async (values) => {
      // Verify captcha on submit
      const token = captchaRef.current.getValue();
      if (token) {
        // Process form submission
      }
    }
  });

  const handleCaptchaChange = (value) => {
    formik.setFieldValue('captcha', value);
  };

  return (
    <form onSubmit={formik.handleSubmit}>
      <TextField
        // ... your existing TextField props
      />
      
      <ReCAPTCHA
        sitekey="YOUR_RECAPTCHA_SITE_KEY"
        ref={captchaRef}
        onChange={handleCaptchaChange}
      />
      
      {formik.touched.captcha && formik.errors.captcha && (
        <Typography color="error">{formik.errors.captcha}</Typography>
      )}
      
      <Button type="submit">Submit</Button>
    </form>
  );
}
  1. Get your site key from Google reCAPTCHA admin console: https://www.google.com/recaptcha/admin

NOTE: for more security you can also validate the token within your backend if needed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment