Gatsby

Handle form submission in Gatsby with Airtable

Send forms directly to your Airtable Base

Table of Contents
  1. What will you need
  2. Setting up Airtable
  3. Setting up the site
  4. Create an Environmental Variable
  5. Build the form
  6. Submit to Airtable
  7. Full code

I am currently building Find Communities Today, a place where you can find communities online. I wanted to allow users to submit their favourite community so I added a page with a form that users could fill out and submit.

Initially, I was using an <iframe> with the form created by Airtable, but the page would take ages to load so I decided to try and make a form myself and sent it to Airtable.

What will you need

  • Airtable Account - This is my referal link.
  • Netlify Account - I'm using environmental variables with Netlify
  • Gatsby - Gatsby handles environmental variables automatically.
  • .env folder - I am going to mention environmental variables

This example will be quite simple. Find Communities Today is being served by Netlify directly from a private repo of GitHub. I am already using Netlify forms for people to report problems with the details of a community, so I didn't want to use Netlify to handle this form.

Also, Airtable is pretty awesome when you need to see the data in a logical way. Since I had created the base in my Airtable, I decided to keep using it to handle the submission of the communities.

Setting up Airtable

Sign up to Airtable if you haven't done so and then log in. There are a lot of templates that you can use, but we will start with a brand new one.

Press the button + Add a Base and from the dropdown menu choose start from scratch, choose a name and press Enter. Airtable will create a spreadsheet with three columns

  • Name
  • Notes
  • Attachments

Fill the first row with some random text and then on the bottom right corner look for the yellow icon with three dots. Click it and choose API Documentation

Then scroll down until you are on the Create record. On the right, you can see the curl call. This will help when we build the API call when submitting the form.

Finally, you will need your API key. Go to your Airtable Account and click on Generate API key, click the input field so you can see the key and copy it.

Setting up the site

If you have never used Gatsby I'd recommend that you read the great tutorial on the official Gatsby site.

Install Gatsby Cli with the command

shell
1npm install --global gatsby-cli

Then run this command to create a new site and change directory into the new folder.

shell
1gatsby new gatsby-site && cd gatsby-site

Finally, open the folder on your favourite code editor and run the following command to get your site running.

shell
1gatsby develop

Create an Environmental Variable

If you are using Netlify, you can just head over to Build & Deploy tab and scroll down until you find the "Build environment variables", make sure your environmental variable starts with GATSBY_<name> so you can store your API key on a variable with the name GATSBY_AIRTABLE for example.

If you just want to test this with Gatsby on your development version, you can just create the file .env.development on the root of your project and then add the API key from airtable like this: AIRTABLE_API=<your API key here>.

Then, when you want to use your API key all you need to do is type process.env.AIRTABLE_API and Gatsby will automatically translate that into your API key.

Build the form

Let's finally build the form. Create a new page on your pages folder, call it contact and add the following code to the page.

js
1import React from "react"
2
3class Contact extends React.component {
4 constructor(props) {
5 super(props)
6 this.state = {}
7 }
8
9 handleSubmit = e => {
10 console.log(this.state);
11
12 e.preventDefault();
13 }
14
15 handleChange = e => this.setState({ [e.target.name]: e.target.value})
16
17 render() {
18 return() (
19 <form>
20 <label>
21 Name
22 <input type="text" name="name" onChange={this.handleChange} />
23 </label>
24 <label>
25 Notes
26 <input type="text" name="notes" onChange={this.handleChange} />
27 </label>
28 <button type="submit">Submit</button>
29 </form>
30 )
31 }
32}

Head over to http://localhost:8000/contact, you will see the quite ugly form that we have created. Open devtools and then fill the form, you will see that whatever you just typed on the input fields will be logged into the console.

As you can see, our component is keeping track of what is being written to the input fields. We can now call Airtable API and send this to our base.

Submit to Airtable

The API post request will be done in the handleSubmit method. Make sure you are on the Create a record in the API Documentation because you will need to know the URL to send the post request.

js
1handleSubmit = e => {
2 const fields = {"fields": {"Name": this.state.name, "Notes": this.state.notes}}
3 fetch("https://api.airtable.com/v0/<account id>/<table name>", {
4 method: "POST",
5 headers: {"Authorization": `Bearer ${process.env.AIRTABLE_API}`,
6 "Content-Type": "application/json"},
7 body: JSON.stringify(fields)
8 })
9 .then(() => alert("Form Sent!"))
10 .catch(error => alert(error))
11
12 e.preventDefault();
13}

Notice that I am using backticks on the Authorization header if you want you can just write it like this: "Bearer " + process.env.AIRTABLE_API". Also, make sure you are passing the environmental variable with the exact name as on your .env.development file.

Full code

So the full working code will look like this

js
1import React from "react"
2
3class Contact extends React.component {
4 constructor(props) {
5 super(props)
6 this.state = {}
7 }
8
9 handleSubmit = e => {
10 const fields = {"fields": {"Name": this.state.name, "Notes": this.state.notes}}
11 fetch("https://api.airtable.com/v0/<account id>/<table name>", {
12 method: "POST",
13 headers: {"Authorization": `Bearer ${process.env.AIRTABLE_API}`,
14 "Content-Type": "application/json"},
15 body: JSON.stringify(fields)
16 })
17 .then(() => alert("Form Sent!"))
18 .catch(error => alert(error))
19
20 e.preventDefault();
21 }
22
23 handleChange = e => this.setState({ [e.target.name]: e.target.value})
24
25 render() {
26 return() (
27 <form>
28 <label>
29 Name
30 <input type="text" name="name" onChange={this.handleChange} />
31 </label>
32 <label>
33 Notes
34 <input type="text" name="notes" onChange={this.handleChange} />
35 </label>
36 <button type="submit">Submit</button>
37 </form>
38 )
39 }
40}

If you are using Netlify don't forget to change the environmental variable to GATSBY_<your env variable name>.

Note that you will need to change the form to use it in production, you probably want to change the input names, the airtable columns names and also create a honeypot to avoid bots from spamming your Airtable base. This was meant to be a quick and simple way to use the Airtable API to submit a form.

Let me know what you think about this. Also, let me know if there is a better way to do this or if you have any issue when trying the code!

Webmentions

0 Like 0 Comment

You might also like these

Learn how to implement HTML5 Geolocation API and VueJs together to get the current location of an user.

Read More
Vue

Weather App - Using geolocation and Vue

Weather App - Using geolocation and Vue

Using VueJs with Axios to connect to OpenWeatherMap API then we build a simple weather web application.

Read More
Vue

Creating a Weather App

Creating a Weather App

Vim is still one of the editors that confuse some developers. This introduction will keep you up to speed with this powerful editor.

Read More
Vim

Introduction to Vim

Introduction to Vim

This article will show you how to setup DynamoDB locally, so you can test your code without having to use your AWS account.

Read More
Databases

How to setup DynamoDB locally

How to setup DynamoDB locally