Add a Contact Form to React

Build a client-side React contact form with fetch and JSON that works with Vite, CRA and any SPA. Submissions go to your inbox, no backend code.

  1. Create a free W3Forms account and a form. Copy the access key shown once.
  2. Optional: in Form → Settings, list your site under Allowed domains, so posts from other sites are marked as spam. Include the port when testing locally (for example localhost:5500).
  3. Paste the markup below. Replace YOUR_ACCESS_KEY with your key.
  4. Submit a test. Check the dashboard inbox and your notification email.

Works with Vite, Create React App, and any SPA. No backend route required — the browser posts straight to W3Forms. Prefer TypeScript? See the Next.js guide for a typed variant.

ContactForm.jsx
import { useState } from "react";

export function ContactForm() {
  const [status, setStatus] = useState("");

  async function handleSubmit(e) {
    e.preventDefault();
    setStatus("Sending…");
    const form = e.currentTarget;
    const res = await fetch("https://api.w3forms.com/submit", {
      method: "POST",
      headers: { "Content-Type": "application/json", Accept: "application/json" },
      body: JSON.stringify(Object.fromEntries(new FormData(form))),
    });
    const data = await res.json();
    if (res.ok && data.success) {
      setStatus("Thanks — your message was sent.");
      form.reset();
    } else {
      setStatus(data.message || data.error || "Something went wrong.");
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      <input type="hidden" name="access_key" value="YOUR_ACCESS_KEY" />
      <label htmlFor="name">Name</label>
      <input id="name" name="name" required />
      <label htmlFor="email">Email</label>
      <input id="email" type="email" name="email" required />
      <label htmlFor="message">Message</label>
      <textarea id="message" name="message" required />
      <input type="text" name="_gotcha" tabIndex={-1} autoComplete="off"
        aria-hidden="true" style={{ position: "absolute", left: "-9999px" }} />
      <button type="submit">Send</button>
      <p role="status">{status}</p>
    </form>
  );
}

Next steps

Other stacks