Setting up Netlify forms with Gatsby

I recently built a website using Gatsby, choosing to host it on the Netlify free tier. One of the features I wanted to try was form handling. Typically, handling form posts requires wiring up and hosting a backend to process requests. Netlify forms allows me deploy a simple static site with zero backend, letting them handle the rest for me. You can read more about the functionality here.

React setup

The setup is relatively straightforwards. Firstly, we need to add in the usual form, input and button tags. Below is a sample component for submitting a user email address.

Notice two extra attributes on the form tag. data-netlify is used to tell Netlfy we want to track this form. data-netlify-honeypot is the name of an input within the form we’ll use to counter bot attacks. Note also that we need to specify a name attribute on the input we’re tracking. This is a key, the input being the value, which will be sent to the Netlify forms api.

The last pieces of markup we need are two hidden inputs.

The first wires up the form name to the Netlify api. The second is the aforementioned honeypot input field for tricking bots. This will be hidden from users, but will likely be completed by any bots informing Netlify to ignore this response.

Hooking it up

Now that the markup is in place, we just need to add some standard React code to track the state of the input and send a POST request for Netlify to capture.

Here we have used React hooks to track the state. A fetch method is then used to send a POST request, encoding the form name and email address response to be sent to the Netlify api.

That’s all folks

And that’s all it takes. Push this to deploy and you’ll notice submissions coming through on the Netlify forms dashboard. It will track a form called register, and will contain a field called email. All this built on a static React site with a stateful front-end. You can see the full code sample here.