TraVision

How To Use Netlify Forms With Gatsby

How To Use Netlify Forms With Gatsby

09-28-2019

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: "",
    }
  }

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("&")
  }

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: "",
    })
  }

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!

NetlifyGatsbyJavascript