t49tran / react-google-recaptcha-v3

Google Recaptcha V3 integration for React
MIT License
427 stars 91 forks source link

How to access the vanilla `onload` function? #157

Open LeeGrobler opened 1 year ago

LeeGrobler commented 1 year ago

I couldn't find anything about this on the npmjs page, which is what brings me here.

When implementing recaptcha with vanilla.js you'd typically import it from a cdn with a script tag, in which case you can add an onload param onto the end of the cdn url, such as with the below:

`

How do I replicate this behaviour with react-google-recaptcha-v3 ? For instance, I imagine an onload prop on the <GoogleReCaptchaProvider /> tag, or something like that, but like I said, the docs don't seem to mention anything about it, so I don't know.

josuearrieta commented 1 year ago

@SeriousLeeTV same here but also interested in onerror vanilla tag. I'm interested in finding a way to reload the script if it fails to load the first time.

gre-dev commented 4 months ago

Here's an alternative way to do that (while the package is not supporting it yet):

import React, { useState, useEffect } from 'react'
import { useGoogleReCaptcha } from 'react-google-recaptcha-v3'

export default function LoginPage() {
    const [token, setToken] = useState<string>('')
    const { executeRecaptcha } = useGoogleReCaptcha()

    const handleFormSubmit = () => {
        if (!token) {
            console.log('Recaptcha not verified yet. Wait for it to verify.')
            return
        }

        // Do your form submission here
        console.log('Form submitted with token:', token)
    }

    useEffect(() => {
        if (!executeRecaptcha) {   // <---- Don't remove this block
            console.log('Recaptcha not loaded yet. Wait for it to load');
            return
        }

        executeRecaptcha('form_submit').then((token) => {
            console.log('loaded')

            setToken(token)
        })
    }, [executeRecaptcha])

    return (
        <>
            <form className="space-y-4 sm:space-y-6" onSubmit={handleFormSubmit}>
                {/* some input fields with a button (you can use the `!token` state to show a loading in the page) */}
            </form>
        </>
    )
}