Contact form

A contact form under a dithered band of your accent: name, email, subject and message. Each field checks itself when you leave it, and the card shows a confirmation in place once the message is sent.

Get in touch

Tell us what you need and we will reply within one working day.

We only use this to reply to you.

Options

Screen
Colour

Code

import { useId, useRef, useState } from "react";
import "./contact-form.css";

/* A contact form on a raised card. Each field checks itself when you leave it,
   and the card shows a confirmation in place once the message is sent.

   <ContactForm onSend={(values) => fetch("/api/contact", { method: "POST", body: JSON.stringify(values) })} /> */
const rules = {
  name: (value) => (value ? "" : "Enter your name."),
  email: (value) => {
    if (!value) return "Enter your email.";
    return /^[^ @]+@[^ @]+[.][^ @]+$/.test(value) ? "" : "That email looks incomplete.";
  },
  subject: (value) => (value ? "" : "Add a subject."),
  message: (value) => {
    if (!value) return "Write a short message.";
    return value.length < 10 ? "Add a little more detail." : "";
  },
};

const empty = { name: "", email: "", subject: "", message: "" };

/* With no onSend, the send is faked with a short wait. */
const pretend = () => new Promise((resolve) => setTimeout(resolve, 900));

export function ContactForm({
  title = "Get in touch",
  lead = "Tell us what you need and we will reply within one working day.",
  note = "We only use this to reply to you.",
  limit = 500,
  onSend = pretend,
}) {
  const id = useId();
  const form = useRef(null);
  const heading = useRef(null);
  const [values, setValues] = useState(empty);
  const [problems, setProblems] = useState({});
  const [state, setState] = useState("");

  const check = (name) => {
    const problem = rules[name](values[name].trim());
    setProblems((now) => ({ ...now, [name]: problem }));
    return !problem;
  };

  const change = (event) => {
    const { name, value } = event.target;
    setValues((now) => ({ ...now, [name]: value }));
    /* A field already marked wrong clears as soon as it is put right. */
    if (problems[name]) setProblems((now) => ({ ...now, [name]: rules[name](value.trim()) }));
  };

  const submit = async (event) => {
    event.preventDefault();
    if (state) return;
    const wrong = Object.keys(rules).filter((name) => !check(name));
    if (wrong.length) {
      form.current.elements[wrong[0]].focus();
      return;
    }
    setState("busy");
    await onSend(values);
    setState("done");
    requestAnimationFrame(() => heading.current && heading.current.focus());
  };

  const again = () => {
    setValues(empty);
    setProblems({});
    setState("");
    requestAnimationFrame(() => form.current.elements.name.focus());
  };

  const field = (name, label, props) => ({
    label: { htmlFor: id + name, children: label },
    input: {
      id: id + name,
      name,
      value: values[name],
      onChange: change,
      onBlur: () => check(name),
      "aria-invalid": name in problems ? Boolean(problems[name]) : undefined,
      "aria-describedby": id + name + "note",
      ...props,
    },
    note: { id: id + name + "note", "aria-live": "polite", children: problems[name] },
  });

  const name = field("name", "Name", { type: "text", autoComplete: "name", placeholder: "Maya Okafor" });
  const email = field("email", "Email", { type: "email", autoComplete: "email", placeholder: "[email protected]" });
  const subject = field("subject", "Subject", { type: "text", placeholder: "A new website" });
  const message = field("message", "Message", { rows: 4, maxLength: limit, placeholder: "What are you working on?" });

  return (
    <section className="dh-contact">
      <form className="dh-contact-card" noValidate ref={form} data-state={state || undefined} onSubmit={submit}>
        <div className="dh-contact-top">
          <svg viewBox="0 0 20 20" aria-hidden="true">
            <path d="M3.500 4A2.500 2.500 0 0 0 1 6.500v.4l8.300 4.400a1.500 1.500 0 0 0 1.400 0L19 6.900v-.4A2.500 2.500 0 0 0 16.500 4h-13ZM19 8.600l-7.600 4a3 3 0 0 1-2.800 0L1 8.600v4.900A2.500 2.500 0 0 0 3.500 16h13a2.500 2.500 0 0 0 2.500-2.500V8.600Z" />
          </svg>
        </div>
        <div className="dh-contact-body" inert={state === "done" ? "" : undefined}>
          <h2>{title}</h2>
          <p className="dh-contact-lead">{lead}</p>
          <div className="dh-contact-grid">
            <div className="dh-contact-field">
              <label {...name.label} />
              <input {...name.input} />
              <small {...name.note} />
            </div>
            <div className="dh-contact-field">
              <label {...email.label} />
              <input {...email.input} />
              <small {...email.note} />
            </div>
            <div className="dh-contact-field dh-contact-wide">
              <label {...subject.label} />
              <input {...subject.input} />
              <small {...subject.note} />
            </div>
            <div className="dh-contact-field dh-contact-wide">
              <label htmlFor={message.label.htmlFor}>
                Message{" "}
                <span className="dh-contact-count">
                  {values.message.length} / {limit}
                </span>
              </label>
              <textarea {...message.input} />
              <small {...message.note} />
            </div>
          </div>
          <div className="dh-contact-foot">
            <p>{note}</p>
            <button className="dh-contact-send" type="submit">
              <i aria-hidden="true" />
              <span>{state === "busy" ? "Sending…" : "Send message"}</span>
            </button>
          </div>
        </div>
        {state === "done" && (
          <div className="dh-contact-done">
            <svg viewBox="0 0 20 20" aria-hidden="true">
              <path
                d="M10 2a8 8 0 1 0 0 16 8 8 0 0 0 0-16Zm3.7 6.3a.9.9 0 0 0-1.3-1.2L9 10.700 7.600 9.300a.9.9 0 0 0-1.300 1.300l2.100 2a.9.9 0 0 0 1.300 0l4-4.300Z"
                fillRule="evenodd"
              />
            </svg>
            <h2 tabIndex={-1} ref={heading}>
              Message sent
            </h2>
            <p>
              Thanks, <span>{values.name.trim().split(" ")[0]}</span>. We will reply to <span>{values.email.trim()}</span> within one
              working day.
            </p>
            <button className="dh-contact-again" type="button" onClick={again}>
              Send another message
            </button>
          </div>
        )}
      </form>
    </section>
  );
}

export function Example() {
  return <ContactForm />;
}

Get in touch

Tell us what you need and we will reply within one working day.

We only use this to reply to you.