- install
npm install react-google-recaptcha
- 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>
);
}
- 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