Try 'magnetic button'
View code

Specification

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

Notes

A search icon that opens into a field, with suggestions dropping in underneath. The field's width animates on a springy curve while the input fades in a moment later, so the placeholder never squeezes into a half-open field.

Results re-mount as the query changes and rise in with a 40ms stagger. With an empty query the list shows recent searches instead of nothing.

Opening focuses the input; Escape clears it, closes it and puts focus back on the icon button.

Code

React and plain CSS
"use client";

import { useEffect, useRef, useState, type CSSProperties } from "react";
import type { LivePreviewProps } from "@/components/live/types";
import styles from "./search-expand.module.css";

const PRODUCTS = ["Canvas tote", "Canvas sneakers", "Linen shirt", "Wool scarf", "Leather belt", "Cotton socks"];
const RECENT = ["Linen shirt", "Wool scarf", "Canvas tote"];
/** Card demo: open, type a word letter by letter, then close. */
const DEMO = [
  { open: false, q: "" },
  { open: true, q: "" },
  { open: true, q: "c" },
  { open: true, q: "ca" },
  { open: true, q: "can" },
  { open: true, q: "canv" },
  { open: true, q: "canvas" },
  { open: true, q: "canvas" },
  { open: false, q: "" },
];

function matches(query: string): string[] {
  const q = query.trim().toLowerCase();
  if (!q) return RECENT;
  return PRODUCTS.filter((p) => p.toLowerCase().split(" ").some((word) => word.startsWith(q)) || p.toLowerCase().startsWith(q)).slice(0, 4);
}

export default function SearchExpand({ active, context }: LivePreviewProps) {
  const [open, setOpen] = useState(false);
  const [query, setQuery] = useState("");
  const [step, setStep] = useState(0);
  const inputRef = useRef<HTMLInputElement>(null);
  const toggleRef = useRef<HTMLButtonElement>(null);
  const demo = active && context === "card";

  // Each time the demo starts, it starts from the first step.
  const [demoRunning, setDemoRunning] = useState(demo);
  if (demoRunning !== demo) {
    setDemoRunning(demo);
    setStep(0);
  }

  useEffect(() => {
    if (!demo) return;
    const id = window.setInterval(() => setStep((s) => s + 1), 420);
    return () => window.clearInterval(id);
  }, [demo]);

  useEffect(() => {
    if (open && context === "detail") inputRef.current?.focus({ preventScroll: true });
  }, [open, context]);

  const state = context === "card" ? (demo ? (DEMO[step % DEMO.length] ?? DEMO[0]) : DEMO[0]) : { open, q: query };
  const isOpen = state?.open ?? false;
  const q = state?.q ?? "";
  const results = matches(q);

  function close() {
    setOpen(false);
    setQuery("");
    toggleRef.current?.focus({ preventScroll: true });
  }

  return (
    <div className={styles.root}>
      <div className={styles.field} data-open={isOpen || undefined}>
        <button
          ref={toggleRef}
          type="button"
          className={styles.toggle}
          aria-label={isOpen ? "Close search" : "Search the shop"}
          aria-expanded={isOpen}
          aria-controls="shop-search"
          tabIndex={context === "card" ? -1 : 0}
          onClick={() => (isOpen ? close() : setOpen(true))}
        >
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" aria-hidden="true">
            <circle cx="11" cy="11" r="6.5" stroke="currentColor" strokeWidth="2.2" />
            <path d="m16 16 4 4" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" />
          </svg>
        </button>
        <input
          ref={inputRef}
          id="shop-search"
          className={styles.input}
          type="search"
          placeholder="Search products"
          aria-label="Search products"
          autoComplete="off"
          maxLength={40}
          value={q}
          tabIndex={isOpen && context === "detail" ? 0 : -1}
          readOnly={context === "card"}
          onChange={(e) => setQuery(e.target.value.slice(0, 40))}
          onKeyDown={(e) => {
            if (e.key === "Escape") {
              e.preventDefault();
              close();
            }
          }}
        />
      </div>
      <div className={styles.results} data-open={isOpen || undefined} aria-live="polite">
        <p className={styles.caption}>{q.trim() ? (results.length ? "Products" : "No matches") : "Recent"}</p>
        <ul className={styles.list}>
          {results.map((name, i) => (
            <li key={name} className={styles.result} style={{ "--i": i } as CSSProperties}>
              <span className={styles.swatch} aria-hidden="true" />
              {name}
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
}

More like this

Label that steps into the outline

TypeForms and inputs

Form in named steps

Type, FeedbackForms and inputs

Currency swap that trades places

Press, Layout AnimationForms and inputs

Sign-up form that waits before it complains

Type, FeedbackForms and inputs

Code field that behaves as one input

Type, FeedbackForms and inputs

Search clear that dissolves word by word

Type, FeedbackForms and inputs