1

I wanted to add the google recaptcha on a form and also it works fine when we reload the page or visit the component for the first time, but if from another component we navigate to the form component using react router (link or navigate), the recaptcha is not loading and also the form is not able to be submitted.

I tried finding about it on google and stackoverflow but could not get any appropriate solution for the problem, I also tried turning off Strict Mode in react but it didn't help.

This is my code:-

import React, { useState, useRef } from 'react';
import { Link } from 'react-router-dom';
import ReCAPTCHA from 'react-google-recaptcha';

export const ContactUs = (props) => {
  const host = process.env.REACT_APP_SERVER_HOST;
  const port = process.env.REACT_APP_SERVER_PORT;
  const { showAlert } = props;

  const recaptchaRef = useRef();

  const [formData, setFormData] = useState({ email: '', password: '' });
  const handleOnChange = (e) => {setFormData({ ...formData, [e.target.name]: e.target.value })};
  const handleSubmit = async (e) => {
    e.preventDefault();

    const recaptchaToken = await recaptchaRef.current.executeAsync(); // Recaptcha token
    recaptchaRef.current.reset(); // Reset recaptcha to make it ready for another check

    const response = await fetch(`http://${host}:${port}/api/contacts/addcontact`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({...formData, recaptchaToken})
    });
    const jsonResponse = await response.json();
    if (jsonResponse.success) {
      document.querySelectorAll('input, textarea').forEach((element) => {element.value=''});
      showAlert('Contact Saved Successfully, I\'ll come back to you soon', 'success');
    }
    else {
      let errorMsg = ""
      jsonResponse.errors.map(error => errorMsg += error.msg + "\n");
      showAlert(errorMsg, 'error');
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      ...

      <ReCAPTCHA
        sitekey={process.env.REACT_APP_RECAPTCHA_SITE_KEY}
        size="invisible"
        ref={recaptchaRef}
      />

      <div className="inputBox">
        <button type="submit" className='btn submit-btn'>Submit</button>
      </div>
    </form>
  )

Full code is available at Github Repo, and this component's code

I also tried using recaptchaRef.current.reset() in useEffect but that also didn't work.

I tried logging the value of recaptchaRef on the console and found that on coming from another component also, the ref is loading and printing the object.

Can someone please guide me to find the solution of the above problem.
Thank you!

Ayush
  • 565
  • 1
  • 7
  • 20

0 Answers0