GatsbyJS Form Installation
Step 1 — Create new form endpoint on Getform
All that's required is a name for your form. You specify a name, and Getform will provide a unique form endpoint to identify your Gatsby form.
Step 2 — Prepare your Gatsby form for your website
You can use the boilerplate code provided on Getform to create your HTML form. It is a basic contact form with email address, name and message fields:
<form accept-charset="UTF-8" action="https://getform.io/f/{unique-endpoint-generated-on-step-1}" method="POST">
<input type="email" name="email" placeholder="Your Email">
<input type="text" name="name" placeholder="Your Name">
<input type="text" name="message" placeholder="Your Message">
<button type="submit">Send</button>
</form>
Step 3 — Create a new blank Gatsby site
Make sure you have the Gatsby CLI installed:
$ npm install -g gatsby-cli
Create a new site
$ gatsby new gatsby-site
Change directories into site folder and run the following:
$ gatsby develop
Gatsby will start a hot-reloading development environment that is accessible by default at localhost:8000
Step 4 - Add a Contact Section to your Gatsby site
Create a new file calledcontact.js under your src/pagesdirectory, change its content with the following code block:
import React, { useState } from "react"
import axios from "axios";
import { Link } from "gatsby"
import Layout from "../components/layout"
const MyForm = () => {
const [serverState, setServerState] = useState({
submitting: false,
status: null
});
const handleServerResponse = (ok, msg, form) => {
setServerState({
submitting: false,
status: { ok, msg }
});
if (ok) {
form.reset();
}
};
const handleOnSubmit = e => {
e.preventDefault();
const form = e.target;
setServerState({ submitting: true });
axios({
method: "post",
url: "https://getform.io/f/{unique-endpoint-generated-on-step-1}",
data: new FormData(form)
})
.then(r => {
handleServerResponse(true, "Thanks!", form);
})
.catch(r => {
handleServerResponse(false, r.response.data.error, form);
});
};
return (
<Layout>
<div>
<div className="col-md-8 mt-5">
<h3>Getform.io Gatsby Form Example</h3>
<form onSubmit={handleOnSubmit}>
<input type="email" name="email" placeholder="Your Email">
<input type="text" name="name" placeholder="Your Name">
<input type="text" name="message" placeholder="Your Message">
<button type="submit">Send</button>
</form>
</div>
</div>
</Layout>
);
};
export default MyForm;
Important: Don't forget to change the action attribute to a form endpoint URL with yours in your contact.js file.Step 5 - Run your Gatsby site locally to finalize setup
Run the following command to see your Gatsby form in action at localhost:8000/contact/:
gatsby develop
That's it! Your Gatsby site is now running Getform.