gatsbyjs / gatsby

The best React-based framework with performance, scalability and security built in.
https://www.gatsbyjs.com
MIT License
55.21k stars 10.33k forks source link

Submit Form Redirect #16326

Closed omartan closed 5 years ago

omartan commented 5 years ago

So I've been looking around for HTML forms for static sites and some that I've found like https://jumprock.co/ uses <input type="hidden" name="after" value="http://google.com"> for redirection, however this will trigger a full page reload.

So what I'm asking is:

  1. Is there any other way to have the value to perhaps change a portion of my page to show a success return message
  2. Or, perhaps a timed based reload? So it'll show a success page and then after 5 seconds load back an empty contact page?

I'm new to Gatsby and React, so more descriptive would be appreciated. Thanks!

elken commented 5 years ago

See the docs for adding forms.

wardpeet commented 5 years ago

Hi @wheelbot,

As @elken suggested we have documentation on how to add a form to gatsby. We also have a more advanced page called how to build a contact form.

Netlify has a blog post how you can do it in react which should also work for gatsby. https://www.netlify.com/blog/2017/07/20/how-to-integrate-netlifys-form-handling-in-a-react-app/

I'm marking this issue as answered and closing it for now but please feel free to re-open this and comment if you would like to continue this discussion. We hope we managed to help and thank you for using Gatsby! 💜

BeauBouchard commented 2 years ago

Although the above resources are great for setting up a form with gatsby, one thing that even year end in 2021 that i think is still missing is the redirect portion of what happens after the form is submitted.

Formal HTML using default behavior would have you hit a different page passing get params. while the recommended methods include preventDefault with no advice as to handle after submit UI. excerpt from the link you provided from netlify almost the same as the other ones on gatsby.

    handleSubmit = e => {
      fetch("/", {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: encode({ "form-name": "contact", ...this.state })
      })
        .then(() => alert("Success!"))
        .catch(error => alert(error));

      e.preventDefault();
    };

Assuming the average user doesn't want to use an alert maybe we could add a brief step to have an after submit section.

Using react-router or react-router-dom and other answers common on the web are not supported by gatsby out of box.

I still believe this question and this issue are relevant today and there should be a new issue / effort to facilitate or support this common UI practice in examples for gatsby.