How to add netlify forms to your Gatsby/React site.

Image for post
Image for post

If you’re only here for the code, scroll all the way to the end to see the github gist.

About Netlify Forms

Netlify Provides a way for us to add forms to our sites out of the box. As long as your site is deployed with Netlify, you can easily add stateful forms to your static site.

The free tier comes with 100 FREE submissions per month and allows users upload files up to 10mb per month.

In your new Gatsby project, create a new React component, let’s call ours Form.js .

Create your own Netlify Form

Import React and the useState hook.

import React, { useState } from "react"

Add the following piece of code that parses the HTML.

const encode = data => {
return Object.keys(data)
.map(key => encodeURIComponent(key) + "=" + encodeURIComponent(data[key]))

Now, within our Form function, let’s create a number of stateful attributes to handle inputs and the different states.

  const [submitted, setSubmitted] = useState("")
const [name, setName] = useState("")
const [email, setEmail] = useState("")
const [message, setMessage] = useState("")
const [submitting, setSubmitting] = useState(false)

Next, let’s create the handleSubmit handler to handle when the form is clicked. Notice that we have given our form a name of waitlist. We have also passed in our name, email and message states.

const handleSubmit = e => {
fetch("/", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: encode({ "form-name": "waitlist", name, email, message }),
.then(() => {
setSubmitted("Thank you for your kind words!")
.catch(error => alert(error))

Finally, let’s create the actual form. There are a few important things to note here. Make sure to use the following attributes on form:
1. name=”waitlist”
2. data-netlify=”true”
3. data-netlify-honeypot=”bot-field”

The name attribute should be the same as the form-name inside the encode function in your handleSubmit event handler.

<input type="hidden" name="form-name" value="waitlist" />
<label htmlFor="name">Your Name: </label>
onChange={({ target }) => setName(target.value)}
placeholder="e.g Morenike Martins-Brown"
<label htmlFor="email">Your Email:</label>
onChange={({ target }) => setEmail(target.value)}
<label htmlFor="message">
Anything else you would like to know (optional)
placeholder="e.g When do you plan on launching?"
onChange={({ target }) => setMessage(target.value)}
<button type="submit">Join waitlist</button>

Make sure not to leave out the hidden input field aswell.

See the full code below. NB — I’m using tailwind css for styling. You can ignore all the styles.

Full code

Written by

Full-stack Engineer. Rails/Node.js/React. I love plantain chips! Reach me at

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store