Try 'magnetic button'
View code

Specification

Catalogue
No. 47 of 110
Interaction
Layout Animation
Element
Form, Input
Preview
Live component
Imports
react 19.3.1
Added

Notes

A short intake where each question slides in as the last one is answered, ending on a summary.

It feels shorter than a form, and each answer is easy to change. The end shows every answer with a Change link before anything is sent.

Question slides 24px and fades in, 280ms cubic-bezier(.22, 1, .36, 1), from the side it comes from. Height glides with the content (the same mechanism as Height that glides). Focus moves to each new question; single, multiple and optional free answers. Unlike the stepper: no steps to see ahead, one decision on screen at a time.

Code

React and plain CSS
"use client";

import { useEffect, useId, useRef, useState, type FormEvent } from "react";
import { AutoHeight } from "@/components/pieces/motion-helpers";
import type { LivePreviewProps } from "@/components/live/types";
import { PieceStage } from "@/components/pieces/stage/PieceStage";
import type { Tour } from "@/components/pieces/stage/tour";
import "@/components/pieces/styles/form-fields.css";
import "./questionnaire.css";

type Q =
  | { id: string; kind: "single"; title: string; options: string[] }
  | { id: string; kind: "multi"; title: string; hint: string; options: string[] }
  | { id: string; kind: "text"; title: string; hint: string };

const QUESTIONS: Q[] = [
  { id: "goal", kind: "single", title: "What would you like help with?", options: ["Getting stronger", "More energy day to day", "Coming back from an injury", "Training for an event"] },
  { id: "days", kind: "multi", title: "Which days could you train?", hint: "Pick any that work", options: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] },
  { id: "note", kind: "text", title: "Anything your coach should know?", hint: "Optional: injuries, times that suit, what has not worked before" },
];

type Answers = Record<string, string | string[]>;

function QuestionnaireDemo() {
  const [step, setStep] = useState(0);
  const [dir, setDir] = useState<"fwd" | "back">("fwd");
  const [answers, setAnswers] = useState<Answers>({ days: [] });
  const [sent, setSent] = useState(false);
  const [nudge, setNudge] = useState(false);
  const heading = useRef<HTMLHeadingElement>(null);
  const moved = useRef(false);
  const uid = useId();
  const done = step === QUESTIONS.length;

  useEffect(() => {
    if (moved.current) heading.current?.focus();
  }, [step, sent]);

  const go = (to: number) => {
    moved.current = true;
    setNudge(false);
    setDir(to > step ? "fwd" : "back");
    setStep(to);
  };
  const q = QUESTIONS[step];
  const answered = (qq: Q) => {
    const a = answers[qq.id];
    if (qq.kind === "text") return true;
    return Array.isArray(a) ? a.length > 0 : Boolean(a);
  };
  const show = (qq: Q) => {
    const a = answers[qq.id];
    if (Array.isArray(a)) return a.length ? a.join(", ") : "None picked";
    return a ? String(a) : "Skipped";
  };

  return (
    <div className="dm">
      <div className="qz">
        <div className="qz-top">
          <span>{done ? "Your answers" : `Question ${step + 1} of ${QUESTIONS.length}`}</span>
          <span className="qz-bar" aria-hidden="true">
            <i style={{ scale: `${(done ? 1 : step / QUESTIONS.length) || 0.02} 1` }} />
          </span>
        </div>
        <AutoHeight>
          {sent ? (
            <div className="qz-step" role="status">
              <h3 ref={heading} tabIndex={-1} className="qz-title">
                Sent to your coach
              </h3>
              <p className="dm-small">They will reply with a first session plan. (Sample: nothing was sent.)</p>
              <div className="qz-nav">
                <button
                  type="button"
                  className="dm-btn"
                  onClick={() => {
                    setSent(false);
                    setAnswers({ days: [] });
                    go(0);
                  }}
                >
                  Start again
                </button>
              </div>
            </div>
          ) : done || !q ? (
            <div key="done" className="qz-step" data-dir={dir}>
              <h3 ref={heading} tabIndex={-1} className="qz-title">
                Check your answers
              </h3>
              <dl className="qz-sum">
                {QUESTIONS.map((qq, i) => (
                  <div key={qq.id}>
                    <dt>{qq.title}</dt>
                    <dd>
                      {show(qq)}{" "}
                      <button type="button" className="qz-link" onClick={() => go(i)} aria-label={`Change: ${qq.title}`}>
                        Change
                      </button>
                    </dd>
                  </div>
                ))}
              </dl>
              <div className="qz-nav">
                <button type="button" className="dm-btn" onClick={() => go(step - 1)}>
                  Back
                </button>
                <button
                  type="button"
                  className="dm-btn"
                  data-variant="solid"
                  onClick={() => {
                    moved.current = true;
                    setSent(true);
                  }}
                >
                  Send to your coach
                </button>
              </div>
            </div>
          ) : (
            <form
              key={q.id}
              className="qz-step"
              data-dir={dir}
              aria-labelledby={`${uid}-${q.id}`}
              onSubmit={(e: FormEvent) => {
                e.preventDefault();
                if (answered(q)) go(step + 1);
                else setNudge(true);
              }}
            >
              <h3 ref={heading} tabIndex={-1} id={`${uid}-${q.id}`} className="qz-title">
                {q.title}
              </h3>
              {q.kind === "single" && (
                <div className="qz-opts" role="radiogroup" aria-labelledby={`${uid}-${q.id}`}>
                  {q.options.map((o) => (
                    <label key={o} className="qz-opt">
                      <input type="radio" name={q.id} checked={answers[q.id] === o} onChange={() => setAnswers((a) => ({ ...a, [q.id]: o }))} />
                      {o}
                    </label>
                  ))}
                </div>
              )}
              {q.kind === "multi" && (
                <fieldset className="qz-days">
                  <legend className="dm-small">{q.hint}</legend>
                  {q.options.map((o) => {
                    const list = (answers[q.id] as string[]) ?? [];
                    return (
                      <label key={o} className="qz-day">
                        <input type="checkbox" checked={list.includes(o)} onChange={() => setAnswers((a) => ({ ...a, [q.id]: list.includes(o) ? list.filter((x) => x !== o) : [...list, o] }))} />
                        {o}
                      </label>
                    );
                  })}
                </fieldset>
              )}
              {q.kind === "text" && (
                <label className="qz-text">
                  <span className="dm-small">{q.hint}</span>
                  <textarea rows={2} value={(answers[q.id] as string) ?? ""} onChange={(e) => setAnswers((a) => ({ ...a, [q.id]: e.target.value }))} />
                </label>
              )}
              <p className="st-err qz-nudge" aria-live="polite">
                {nudge && !answered(q) ? "Pick an answer to continue" : ""}
              </p>
              <div className="qz-nav">
                {step > 0 && (
                  <button type="button" className="dm-btn" onClick={() => go(step - 1)}>
                    Back
                  </button>
                )}
                {q.kind === "text" && !answers[q.id] ? (
                  <button type="submit" className="dm-btn" data-variant="solid">
                    Skip
                  </button>
                ) : (
                  <button type="submit" className="dm-btn" data-variant="solid" aria-disabled={!answered(q)}>
                    Next
                  </button>
                )}
              </div>
            </form>
          )}
        </AutoHeight>
      </div>
    </div>
  );
}

// What a hovered card shows: the piece used the way a visitor would.
const TOUR: Tour = [
  { click: ".qz-opt input", nth: 1, wait: 600 },
  { click: 'button[type="submit"]', wait: 900 },
  { click: ".qz-day input", nth: 0, wait: 300 },
  { click: ".qz-day input", nth: 2, wait: 300 },
  { click: ".qz-day input", nth: 4, wait: 600 },
  { click: 'button[type="submit"]', wait: 900 },
  { click: 'button[type="submit"]', wait: 2200 },
];

export default function QuestionnaireEntry(props: LivePreviewProps) {
  return (
    <PieceStage {...props} label="One question at a time" tour={TOUR}>
      <QuestionnaireDemo />
    </PieceStage>
  );
}

More like this

Form in named steps

Type, FeedbackForms and inputs

Cookie choice that folds away

FeedbackOverlays and toasts

File upload with progress per file

Loading, FeedbackForms and inputs

Button that grows into its form

Press, TypeButtons and toggles

Video poster that opens the player

Press, Layout AnimationMedia and galleries

Tabs you can swipe

Drag, Layout AnimationTabs