user11834465
user11834465

Reputation:

Why does the page reload after submitting form? (React/Netlify/react-recaptcha)

Problem: I am using the react-recaptcha library to show a Google reCAPTCHA v2 in my ReactJS form. The UI seems to look fine, but when I submit the form, the page reloads and I never receive any form submissions on Netlify.

Attempt: Removing the reCAPTCHA and the form works fine, and I receive the form submissions in Netlify, so the problem has something to do with the reCAPTCHA.

I am using create-react-app for react website.

Following the Netlify form documentation, I have signed up for a reCAPTCHA v2 API key pair from Google, and set two environmental variables within the site settings.

My Netlify environmental variables settings

The relevant code is available in this gist: Github Gist

In theory, putting this in html:

<script
  src="https://www.google.com/recaptcha/api.js"
  async
  defer
></script>

And this in the Form.js:

 <Recaptcha
     sitekey={process.env.REACT_APP_SITE_RECAPTCHA_KEY}
     theme="dark"
 />

should have made it work, but I'm not sure what is causing the page to reload after the form submits.

Any help would be greatly appreciated! Thank you.

Edit: This is not an e.preventDefault() problem, because I am using Netlify to handle form submissions. Upon form submission, it will redirect the user to a default form success page. The problem here is once I add the reCAPTCHA inside the form, the page reloads without sending me the form data nor to the redirected page. And that is even after I add a e.preventDefault() handler on form submission.

Upvotes: 0

Views: 1434

Answers (2)

user11834465
user11834465

Reputation:

What worked for me

In Netlify, I added a REACT_APP_ prefix version of the env var(s).

E.g. if I had these env vars:

  1. SITE_KEY=123
  2. SITE_SECRET=abc

I added these:

  1. REACT_APP_SITE_KEY=123
  2. REACT_APP_SITE_SECRET=abc

So in total in the Netlify dashboard I would have:

  1. SITE_KEY=123
  2. SITE_SECRET=abc
  3. REACT_APP_SITE_KEY=123
  4. REACT_APP_SITE_SECRET=abc

Upvotes: 0

John Ruddell
John Ruddell

Reputation: 25852

Like described in the comments, forms submit the page, thats the intended behavior. If you want to avoid this then call preventDefault on the event.

<form onSubmit={this.handleSubmit}

and the handler would look like this

handleSubmit(event) {
  event.preventDefault()

Upvotes: 1

Related Questions