Gatsby Guide
Add A Contact Form To Gatsby
Here is a guide for integrating Fabform with a Gatsby site:
Step 1: Setting up a Gatsby site
Ensure you have the Gatsby CLI installed:
npm install -g gatsby-cli
Create a new Gatsby site:
gatsby new gatsby-site
Navigate into your site folder and start the development server:
cd gatsby-sitegatsby develop
Gatsby will start a hot-reloading development environment accessible by default at localhost:8000
.
Step 2: Adding a Form to your Gatsby site
- Create a Form Component: Create a new file called
contact.js
under yoursrc/pages
directory and update its content with the following code block:
import React, { useState } from "react";import axios from "axios";import Layout from "../components/layout";
const Contact = () => { 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://fabform.io/f/{your-form-endpoint}", data: new FormData(form) }) .then(r => { handleServerResponse(true, "Thanks!", form); }) .catch(r => { handleServerResponse(false, r.response.data.error, form); }); };
return ( <Layout> <div className="col-md-8 mt-5"> <h3>Fabform.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> </Layout> );};
export default Contact;
Note: Replace {your-form-endpoint}
with the unique form endpoint provided by Fabform.
Step 3: 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 integrated with Fabform for handling form submissions.