I am very new to react/hooks and struggling hard to get Google recaptcha working properly.
This is how my app.js looks like:
import ConfirmationPage from './Pages/ConfirmationPage';
function App() {
const [email, setEmail] = React.useState('');
const captchaRef = useRef({});
function someFunction() {
//Uses captchaRef to do something
}
return (
<ConfirmationPage email={email} setEmail={setEmail} captchaRef={captchaRef}></ConfirmationPage>
);
}
And this is how my ConfirmationPage.js looks like:
import ReCAPTCHA from "react-google-recaptcha";
import { Grid, TextField, Divider } from '@material-ui/core';
export default function ConfirmationPage({email, setEmail, captchaRef}) {
function onChange(value) {
console.log("Captcha Verified");
}
function handleEmailBlur(email){
setEmail(email);
}
return (
<>
<TextField
required
id="txt_summary_email"
label={'Email'}
defaultValue={email}
className={classes.FulltextField}
margin="normal"
onBlur={event=>handleEmailBlur(event.target.value)}
/>
<ReCAPTCHA
ref ={captchaRef}
sitekey={process.env.REACT_APP_CAPTCHAKEY}
onChange={onChange}
/>
</>
);
The problem occurs when a user tries to enter email value into txt_summary_email TextField, Captcha re-renders itself and loses its validation status. In other words, validate Captcha by clicking the empty box and try to enter email into the text field, Captcha will lose the validation check.
This is happening because of setEmail(email) in handleEmailBlur function. If I comment out setEmail(email), Captcha does not re-render itself. It looks like setting state in app.js somehow triggers the captcha to re-load.
How can I prevent the captcha from being re-rendered when setState is triggered?
Thank you very much for your help!