Dev Helpers
← Back

Dialog with a focus return

Import and render <DialogWithAFocusReturn /> in a React project.

Open this example in the interactive library

Live preview

Source code

// components/DialogWithAFocusReturn.tsx

import { useRef } from "react";

import type { ReactNode } from "react";

export default function DialogWithAFocusReturn({
  title = "Delivery",
  children = "Arrives in two days.",
}: { title?: string; children?: ReactNode } = {}) {
  const dialog = useRef<HTMLDialogElement>(null);
  return (
    <>
      <button onClick={() => dialog.current?.showModal()}>{title}</button>
      <dialog ref={dialog} aria-label={title}>
        {children}
        <form method="dialog">
          <button>Close</button>
        </form>
      </dialog>
    </>
  );
}