Written by: Geoffrey Callaghan

Create a Working Contact Form for your Static Website

Create A Working Contact Form For Your Static Website

To create a working contact form for your static website using FabForm, you need to follow these steps:

Step 1: Set Up FabForm

First, you need to install FabForm. You can do this via npm or yarn:

npm install @fabulas/ft-form

or

yarn add @fabulas/ft-form

Step 2: Create Your Contact Form Component

Next, create a React component for your contact form. Here’s an example:

// ContactForm.js
import React from 'react';
import { useForm } from '@fabulas/ft-form';

const ContactForm = () => {
  const { values, handleSubmit, handleChange } = useForm({
    initialValues: { name: '', email: '', message: '' },
    onSubmit: async (values) => {
      try {
        const response = await fetch('/api/contact', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(values),
        });
        if (response.ok) {
          console.log('Form submitted successfully');
        } else {
          console.error('Form submission failed');
        }
      } catch (error) {
        console.error('Error submitting form:', error);
      }
    },
  });

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="name">Name:</label>
        <input type="text" id="name" name="name" value={values.name} onChange={handleChange} required />
      </div>
      <div>
        <label htmlFor="email">Email:</label>
        <input type="email" id="email" name="email" value={values.email} onChange={handleChange} required />
      </div>
      <div>
        <label htmlFor="message">Message:</label>
        <textarea id="message" name="message" value={values.message} onChange={handleChange} required />
      </div>
      <button type="submit">Submit</button>
    </form>
  );
};

export default ContactForm;

Step 3: Create a Serverless Function

Now, you need to create a serverless function to handle the form submission. In a Next.js project, this would be placed in the pages/api directory. Here’s an example:

// pages/api/contact.js
export default async function handler(req, res) {
  if (req.method === 'POST') {
    const { name, email, message } = req.body;

    // Example: Send email using a third-party service
    try {
      // Code to send email
      console.log(`Message received from ${name} <${email}>: ${message}`);
      res.status(200).json({ message: 'Form submitted successfully' });
    } catch (error) {
      console.error('Error submitting form:', error);
      res.status(500).json({ message: 'Failed to submit form' });
    }
  } else {
    res.setHeader('Allow', ['POST']);
    res.status(405).end(`Method ${req.method} Not Allowed`);
  }
}

Step 4: Use the Contact Form Component

Finally, use the ContactForm component in your page:

// ContactPage.js
import React from 'react';
import ContactForm from './ContactForm';

const ContactPage = () => {
  return (
    <div>
      <h1>Contact Us</h1>
      <ContactForm />
    </div>
  );
};

export default ContactPage;

Step 5: Deploy Your Website

Deploy your static website, including the FabForm-powered contact form and the serverless function, to a platform like Vercel, Netlify, or AWS Amplify.

Now, your static website has a working contact form powered by FabForm, and form submissions are handled securely by the serverless function.