Try 'magnetic button'
View code

Specification

Catalogue
No. 29 of 110
Interaction
Press, Type, Layout Animation
Element
Button, Form, Overlay
Preview
Live component
Imports
react 19.3.1, framer-motion 12.40.0
Added

Notes

Ask a question opens into a short form in place, then settles into a confirmation where the button was.

One object carries the whole request, so nothing appears somewhere else. The button's words slide up to become the form's title, and Escape or Cancel shrinks it back.

Spring, bounce 0.1, 0.45s (framer-motion layout); the title travels with layoutId. Errors under each field; Send shows Sending, then the confirmation. Escape, Cancel or a click outside closes; focus returns to the button. Server simulated; a real build confirms only after the server accepts.

Code

React and plain CSS
"use client";

import { useEffect, useId, useRef, useState, type FormEvent } from "react";
import { motion, MotionConfig } from "framer-motion";
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 "./morph-popover.css";

type MorphState = "closed" | "open" | "busy" | "sent";

function MorphPopoverDemo() {
  const [state, setState] = useState<MorphState>("closed");
  const [email, setEmail] = useState("");
  const [question, setQuestion] = useState("");
  const [tried, setTried] = useState(false);
  const wrap = useRef<HTMLDivElement>(null);
  const trigger = useRef<HTMLButtonElement>(null);
  const firstField = useRef<HTMLInputElement>(null);
  const done = useRef<HTMLHeadingElement>(null);
  const prev = useRef<MorphState>("closed");
  const timer = useRef<number | undefined>(undefined);
  const uid = useId();

  useEffect(() => () => window.clearTimeout(timer.current), []);
  useEffect(() => {
    if (state === "open" && prev.current === "closed") firstField.current?.focus();
    if (state === "closed" && prev.current !== "closed") trigger.current?.focus();
    if (state === "sent") done.current?.focus();
    prev.current = state;
  }, [state]);
  useEffect(() => {
    if (state !== "open") return;
    const onDown = (e: PointerEvent) => {
      if (wrap.current && e.target instanceof Node && !wrap.current.contains(e.target)) setState("closed");
    };
    document.addEventListener("pointerdown", onDown);
    return () => document.removeEventListener("pointerdown", onDown);
  }, [state]);

  const emailErr = !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim()) ? "Enter an email address we can reply to" : "";
  const qErr = question.trim().length < 3 ? "Write your question" : "";
  const send = (e: FormEvent) => {
    e.preventDefault();
    setTried(true);
    if (emailErr || qErr) {
      (emailErr ? firstField.current : wrap.current?.querySelector("textarea"))?.focus();
      return;
    }
    setState("busy");
    // Simulated server. A real build shows the confirmation only once the server accepts.
    timer.current = window.setTimeout(() => setState("sent"), 900);
  };
  const reset = () => {
    setEmail("");
    setQuestion("");
    setTried(false);
    setState("closed");
  };

  return (
    <div className="dm">
      <MotionConfig reducedMotion="user" transition={{ type: "spring", bounce: 0.1, duration: 0.45 }}>
        <motion.div
          ref={wrap}
          layout
          className="mp"
          data-state={state}
          style={{ borderRadius: state === "closed" ? 999 : 18 }}
          onKeyDown={(e) => {
            if (e.key === "Escape" && state === "open") {
              e.stopPropagation();
              setState("closed");
            }
          }}
        >
          {state === "closed" ? (
            <button ref={trigger} type="button" className="mp-trigger" aria-expanded={false} aria-controls={`${uid}-form`} onClick={() => setState("open")}>
              <motion.span layoutId={`${uid}-title`} layout="position">
                Ask a question
              </motion.span>
            </button>
          ) : state === "sent" ? (
            <motion.div layout="position" className="mp-done" role="status" initial={{ opacity: 0 }} animate={{ opacity: 1 }}>
              <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                <path d="m5 12.5 4.5 4.5L19 7.5" />
              </svg>
              <h3 ref={done} tabIndex={-1}>
                Sent. We will reply to {email.trim()}.
              </h3>
              <button type="button" className="dm-btn" onClick={reset}>
                Done
              </button>
            </motion.div>
          ) : (
            <form id={`${uid}-form`} className="mp-form" noValidate onSubmit={send} aria-labelledby={`${uid}-h`}>
              <motion.h3 id={`${uid}-h`} layoutId={`${uid}-title`} layout="position">
                Ask a question
              </motion.h3>
              <motion.div layout="position" className="mp-fields" initial={{ opacity: 0 }} animate={{ opacity: 1, transition: { delay: 0.08, duration: 0.2 } }}>
                <div className="st-field">
                  <label htmlFor={`${uid}-em`}>Your email</label>
                  <input id={`${uid}-em`} ref={firstField} type="email" autoComplete="email" value={email} onChange={(e) => setEmail(e.target.value)} aria-invalid={tried && !!emailErr} aria-describedby={tried && emailErr ? `${uid}-ee` : undefined} />
                  {tried && emailErr && (
                    <span className="st-err" id={`${uid}-ee`}>
                      {emailErr}
                    </span>
                  )}
                </div>
                <div className="st-field">
                  <label htmlFor={`${uid}-qq`}>Question</label>
                  <textarea id={`${uid}-qq`} rows={2} value={question} onChange={(e) => setQuestion(e.target.value)} aria-invalid={tried && !!qErr} aria-describedby={tried && qErr ? `${uid}-qe` : undefined} />
                  {tried && qErr && (
                    <span className="st-err" id={`${uid}-qe`}>
                      {qErr}
                    </span>
                  )}
                </div>
                <div className="qz-nav">
                  <button type="button" className="dm-btn" onClick={() => setState("closed")}>
                    Cancel
                  </button>
                  <button type="submit" className="dm-btn" data-variant="solid" aria-busy={state === "busy"} disabled={state === "busy"}>
                    {state === "busy" ? "Sending…" : "Send"}
                  </button>
                </div>
              </motion.div>
            </form>
          )}
        </motion.div>
      </MotionConfig>
    </div>
  );
}

// What a hovered card shows: the piece used the way a visitor would.
const TOUR: Tour = [
  { click: ".mp-trigger", wait: 2200 },
  { click: ".dm-btn", text: "Cancel", wait: 900 },
];

export default function MorphPopoverEntry(props: LivePreviewProps) {
  return (
    <PieceStage {...props} label="Button that grows into its form" tour={TOUR}>
      <MorphPopoverDemo />
    </PieceStage>
  );
}

More like this

Video poster that opens the player

Press, Layout AnimationMedia and galleries

Cookie choice that folds away

FeedbackOverlays and toasts

One question at a time

Layout AnimationForms and inputs

Form in named steps

Type, FeedbackForms and inputs

Several services in one field

Press, TypeForms and inputs

Menu that opens into link cards

Press, Layout AnimationNavigation