0

I have a Next.js app using react-google-recaptcha. I use it in a multi-part form where I change the view as the user advances through the form. When the user gets to the view having the ReCAPTCHA, it will load correctly. But if the user clicks 'Back' (changing the view state and causing the ReCAPTCHA to be unloaded), and then clicks 'Next' to go back to the view with the ReCAPTCHA, it does not render.

Is there a way to correct this?

const View1 = ({onNext}) => ...

const View2 = ({onNext, onBack}) => ...

const View3 = ({onBack}) => {

  const recaptchaRef = createRef()

  const onReCAPTCHAChange = (captchaCode) => {
    if(!captchaCode) return
    console.log(captchaCode)
  }

  return (
    <div className="p-4 rounded bg-gray-100">
      <div>View 3</div>
      <div>
      <ReCAPTCHA
        ref={recaptchaRef}
        size="compact" // invisible, normal, compact
        sitekey={process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY}
        onChange={onReCAPTCHAChange}
        badge="inline" // bottomright, bottomleft, inline
      />
      </div>
      <div className="flex items-center gap-4">
        <button className="btn-primary" onClick={onBack}>Back</button>
      </div>
    </div>
  )
}

export default function Sandbox() {

  const [view, setView] = useState(1)

  return (
    <div>

      {
        view===1 ? <View1 onNext={()=>setView(2)} /> :
        view===2 ? <View2 onNext={()=>setView(3)} onBack={()=>setView(1)} /> :
        view===3 ? <View3 onBack={()=>setView(2)} /> : null
      }

    </div>
  )
}
good1492
  • 161
  • 1
  • 10

1 Answers1

0

I guess you are using Reactjs ver 18, I fixed it by following this https://github.com/dozoisch/react-google-recaptcha/issues/250 we need to update react-google-captcha to version 3.0.0 beta