How To Build a Contact Form with React

    Learn how build a React form to collect contact form submissions and receive email notifications.

    1Prepare your project

    Install the React helper library in your project:

    npm install @statickit/react

    Then add the StaticKitProvider to your top-level app component. For example, if you are using Next.js, here's what your pages/_app.js file might look like:

    import { StaticKitProvider } from '@statickit/react';
    function App({ Component, pageProps }) {
    return (
    <StaticKitProvider site="{your-site-id}">
    <Component {...pageProps} />
    </StaticKitProvider>
    );
    }
    export default App;

    2Configure your function

    In your statickit.json file, add a function to send you a notification:

    {
    "functions": {
    "sendContactEmail": {
    "type": "sendNotification",
    "to": "{your-email-address}"
    }
    }
    }

    Then, deploy your changes to StaticKit:

    statickit deploy -k <your-deploy-key>

    3Build your form

    Here's an example component that calls your sendContactEmail function in the form submit handler.

    import React, { useState } from 'react';
    import { useStaticKit, ValidationError } from '@statickit/react';
    import { sendContactEmail } from '@statickit/functions';
    function ContactForm(props) {
    const client = useStaticKit();
    const [email, setEmail] = useState('');
    const [message, setMessage] = useState('');
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [isSubmitted, setIsSubmitted] = useState(false);
    const [errors, setErrors] = useState([]);
    const handleSubmit = async e => {
    e.preventDefault();
    setErrors([]);
    setIsSubmitting(true);
    let resp = await sendContactEmail(client, {
    subject: `${email} submitted the contact form`,
    replyTo: email,
    fields: { message }
    });
    switch (resp.status) {
    case 'ok':
    setIsSubmitted(true);
    break;
    case 'argumentError':
    setErrors(resp.errors);
    setIsSubmitting(false);
    break;
    default:
    setIsSubmitting(false);
    break;
    }
    }
    if (isSubmitted) {
    return <p>Thanks for joining!</p>;
    }
    return (
    <form onSubmit={handleSubmit}>
    <label htmlFor="email">
    Email Address
    </label>
    <input
    id="email"
    type="email"
    name="email"
    onChange={e => setEmail(e.target.value)}
    value={email}
    />
    <ValidationError
    prefix="Email"
    field="replyTo"
    errors={errors}
    />
    <textarea
    id="message"
    name="message"
    onChange={e => setMessage(e.target.value)}
    value={message}
    />
    <button type="submit" disabled={isSubmitting}>
    Submit
    </button>
    </form>
    );
    }