'How to add a google-recaptcha v3 to a functional react component with a form?
I have a ready-made form in React
I'm trying to add a captcha to it but it would seem that with the only correct option the captcha reload infinity loops
I didt think that in such a simple task in React there could be so many problems
import { GoogleReCaptchaProvider, GoogleReCaptcha } from 'react-google-recaptcha-v3'
type Props = {
onSubmit: (values: AuthRequest) => Promise<AuthResponse>
}
function AuthForm(props: Props) {
const [token, setToken] = useState('')
return (
<div className={cn('container')}>
<GoogleReCaptchaProvider reCaptchaKey="[key]">
<Form
onSubmit={handlers.submit}
render={({ handleSubmit }) => (
<form onSubmit={handleSubmit}>
<FormField name={'email'} />
<div>
<FormField name={'password'} />
</div>
<GoogleReCaptcha
onVerify={(token) => {
setToken(token)
}}
/>
<div>
<Button type="submit">Submit</Button>
</div>
</form>
)}
/>
</GoogleReCaptchaProvider>
</div>
)
}
export { AuthForm }
Solution 1:[1]
I solved it like this
import { GoogleReCaptchaProvider, GoogleReCaptcha } from 'react-google-recaptcha-v3'
type Props = {
onSubmit: (values: AuthRequest) => Promise<AuthResponse>
}
function AuthForm(props: Props) {
const [token, setToken] = useState('')
const verifyRecaptchaCallback = React.useCallback((token) => {
setToken(token)
}, []);
return (
<div className={cn('container')}>
<GoogleReCaptchaProvider reCaptchaKey="[key]">
<Form
onSubmit={handlers.submit}
render={({ handleSubmit }) => (
<form onSubmit={handleSubmit}>
<FormField name={'email'} />
<div>
<FormField name={'password'} />
</div>
<GoogleReCaptcha
onVerify={verifyRecaptchaCallback}
/>
<div>
<Button type="submit">Submit</Button>
</div>
</form>
)}
/>
</GoogleReCaptchaProvider>
</div>
)
}
export { AuthForm }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | David |