Sougata Mukherjee
Sougata Mukherjee

Reputation: 603

Why does reCaptcha disappear when I navigate to another page?

if I want to load the captcha by clicking refresh button its loading, but when we navigate to another page and clicking browser back button then captcha is going to disappear. How to resolve that problem that every time (either you refresh or clicking from browser back button) captcha should shown

import React, { useState } from "react";
import Recaptcha from "react-recaptcha";
export default function DropDown() {
  const grecaptchaObject = window.grecaptcha;
  function captchaVerify(response) {
    if (response !== "") {
      //some code
    } else if ((response === "")) {
      //some code 
    }
  }
  function recaptchaLoaded() {
  }
  return (
    <>
      <div>
        <Recaptcha
          sitekey="Your-Site-Key"
          render="explicit"
          onloadCallback={recaptchaLoaded}
          verifyCallback={captchaVerify}
          grecaptcha={grecaptchaObject}
        />
      </div>
    </>
  );
}

Upvotes: 3

Views: 2681

Answers (2)

Briant Grijalva
Briant Grijalva

Reputation: 66

Try to disabling the <React.StrictMode> in index.js like this:

const root = createRoot(container);
root.render(
 // <React.StrictMode>
    <App />
 // </React.StrictMode>
);

Upvotes: 5

Ashraf Slamang
Ashraf Slamang

Reputation: 1013

You have to use the reset method. From the docs:

Explicitly reset the reCAPTCHA widget

The reCAPTCHA widget can be manually reset by accessing the component instance via a callback ref and calling .reset() on the instance.

var Recaptcha = require('react-recaptcha');
 
// create a variable to store the component instance
let recaptchaInstance;
 
// create a reset function
const resetRecaptcha = () => {
  recaptchaInstance.reset();  
};
 
ReactDOM.render(
  <div>
    <Recaptcha
      ref={e => recaptchaInstance = e}
      sitekey="xxxxxxxxxxxxxxxxxxxx"
    />
    <button
      onClick={resetRecaptcha}
    >
     Reset
    </button>
  </div>,
  document.getElementById('example')
);

To get this to work on each load, you can take advantage of the useEffect hook:

useEffect(() => {
  recaptchaInstance.reset();
, []);

Upvotes: 1

Related Questions