Contact Form for Gatsby

Code example for Gatsby that adds a full-featured contact form to your site based on GatsbyJS

Contact Form for Gatsby

Contact Form Code Example for Gatsby.js

Gatsby is a static site generator for React. With Gatsby you can build modern static websites with blazing-fast performance, progressive web app capabilities, and easy client-side routing. Use this contact form by replacing your own API key to make it work.

import { useState } from "react";

export default function Form() {
  const [responseMessage, setResponseMessage] = useState("");

  async function handleSubmit(event) {
    event.preventDefault();
    const formData = new FormData(event.target);

    const object = Object.fromEntries(formData);
    const json = JSON.stringify(object);

    const response = await fetch("https://formbold.com/s/unique_form_id", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
      body: json,
    });
    const result = await response.json();

    if (response.ok) {
      setResponseMessage(result.message);
      event.target.reset();
    }
    setResponseMessage(result.message || "Something went wrong");
    setTimeout(() => setResponseMessage(""), 3000);
  }
  return (
    <>
      <div className="container">
        <div className="form-wrapper">
          <form onSubmit={handleSubmit}>
            <div>
              <input
                type="email"
                name="email"
                id="email"
                placeholder="Your Email"
                required
              />
            </div>

            <div>
              <input
                type="text"
                name="subject"
                id="subject"
                placeholder="Your subject"
                required
              />
            </div>

            <div>
              <textarea
                name="message"
                id="message"
                rows="6"
                placeholder="Your Message"
                required
              ></textarea>
            </div>

            <div>
              <button type="submit">Submit</button>
            </div>

            <div>
              <p>{responseMessage}</p>
            </div>
          </form>
        </div>
      </div>
    </>
  );
}

Create a Form to Connect Apps