DEV Community

Cover image for How To Use Netlify Forms With Gatsby
Travis Ramos
Travis Ramos

Posted on • Updated on • Originally published at travislramos.com

How To Use Netlify Forms With Gatsby

This article assumes you have some basic knowledge of Gatsby and Netlify.

How do you do it?

Using Netlify's built-in form handling with Gatsby should be simple and intuitive, but sadly it's not that simple.
Well it is, it just requires some extra configuration not detailed in the documentation. So let’s get started!

Normally adding either a Netlify attribute or data-netlify="true" to your form tag is all you'd have to do and Netlify will do the rest for you. If your creating your application with Gatsby, this isn't the case. In order for Netlify to actually see the form, you need to create a reference to the component where your form code will be when your component is rendered. This is as simple as referencing your component in the constructor like this.

constructor(props) {
    super(props)
    this.ContactForm = React.createRef()
    this.state = {
      name: "",
      email: "",
      message: "",
    }
  }
Enter fullscreen mode Exit fullscreen mode

The reason for this is because Gatsby is not rendered during runtime, it instead generates HTML content during build time.
At this point, the information your users will add to the form will be in the form of an object. In order to pass this object along in your POST request, you will need to transform this object into a query string parameter. Add the snippet below under your constructor to be used later in your submit function.

encode = data => {
    return Object.keys(data)
      .map(key => encodeURIComponent(key) + "=" + encodeURIComponent(data[key]))
      .join("&")
  }
Enter fullscreen mode Exit fullscreen mode

This will not only transform your object, but it will also encode your key/value pairs you pass into it.

Almost there, just a few more steps!

The next part is actually creating your function to handle your form submission. First create a variable to hold your form reference from a few steps above. Then pass in this variable you created inside the body of your HTTP-request like so.

handleSubmit = event => {
    event.preventDefault()
    const form = this.ContactForm.current
    fetch("/", {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: this.encode({
        "form-name": form.getAttribute("name"),
        ...this.state,
      }),
    })
      .then(() => navigate("/"))
      .catch(error => alert(error))

    this.setState({
      name: "",
      email: "",
      message: "",
    })
  }
Enter fullscreen mode Exit fullscreen mode

The final part is writing the code for your form and including either a Netlify attribute or data-netlify="true" in your form tag as discussed above.
Don't forget to include a name attribute in the form tag as well so your HTTP-request can find the form you just created.
And thats it!
You will find all of the submissions to these forms in the Forms tab of your site dashboard in Netlify.

I hope this article was helpful, and if you enjoyed it, checkout some of the other articles I have written!

Top comments (8)

Collapse
 
johnrock profile image
John Rock • Edited

Only thing I am doing is setting the state and adding a hidden field like below and my forms work fine with Gatsby and Netlify.
<input type="hidden" name="form-name" value="Newsletter" />

I am doing it wrong or is this over engineered?

Collapse
 
travislramos profile image
Travis Ramos

It depends on if you are using AJAX to submit the form. I'm guessing you are not since it is working fine for you. If you where however, you would need to make sure the content is URL-encoded to work properly.

Hope this helped!

Collapse
 
johnrock profile image
John Rock

Got it, that makes sense. Good read thanks!

Collapse
 
soldier profile image
Edgardo Ramírez

Is not working for me.

In the Network tab I am seeing a 303 error code response when I submit the form with this demo data

form-name=contact&name=a&email=b%40b.com&company=Edgar%201&message=a&bot-field=true

Collapse
 
travislramos profile image
Travis Ramos

Could you shoot me a link to your repo and I can take a look?

Also did you create an active form on your Netlify dashboard?

Collapse
 
devanshh profile image
Devansh Agarwal

Well, undoubtedly, GatsbyJS & Netlify CMS are the perfect match. I mean the beauty with which they complement each other's attribute is appreciable!

Collapse
 
travislramos profile image
Travis Ramos

Yes they complement each other very well!

Collapse
 
devanshh profile image
Info Comment hidden by post author - thread only accessible via permalink
Devansh Agarwal

Correct. And this perfect pair is lucidly explained in this Medium Blogpost of mine.

Some comments have been hidden by the post's author - find out more