React - Add Google reCAPTCHA to form
In this tutorial we will add Google reCAPTCHA to a form in Reactjs. reCAPTCHA protects from spam and abuse.
Visit Google reCAPTCHA
On the top right side click plus icon
Enter label for your site
From reCAPTCHA type, select reCAPTCHA v2
In Domains, add your website without http or https
Accept the terms of service and click Submit
Upon submission, you will get the site key, store it somewhere as we will use this in code.
In your react project root level open terminal and run
npm install react-google-recaptcha
Here is the example code
import React, { useState } from “react” import ReCAPTCHA from "react-google-recaptcha"; const Form = () => { const [name, setName] = useState("") const [capVal, setCapVal] = useState(); const handleSubmit = async e => { e.preventDefault() try { // api request here } catch (err) { console.log(err) } setCapVal(); } return ( <form onSubmit={handleSubmit}> <input type="text" placeholder="Enter your name" name="name" value={name} onChange={e=> setName(e.target.value)} required /> <ReCAPTCHA sitekey="your-sitekey-here" onChange={(val) => setCapVal(val)} /> <div> <input type="submit" value="Send" disabled={!capVal} /> </div> </form> ) } export default Form
So this is a simple form with only name field. We imported ReCAPTCHA from react-google-recaptcha and then created two states, name and capVal.
We added an onChange function to ReCAPTCHA component where we are updating the capVal state. Also, we have disabled the button if capVal is null which means user will not be able to click the Send button if reCAPTCHA is not checked.
That's how you can protect form on your website with google reCAPTCHA from spam.