Hook that queues focus requests until the element mounts
Clicking “Rename” on a file swaps its label for a text input, and the input should be focused with the old name selected. The tricky part is timing: when the click handler runs, the input does not exist yet. It only appears after React re-renders. Implement a React hook, useFocusRequest, that lets you ask for focus at any time and applies it as soon as the element is there.
function useFocusRequest<T extends HTMLElement>(): {
ref: (node: T | null) => void;
requestFocus: (options?: { select?: boolean }) => void;
}
ref is a callback ref. Attach it with <input ref={ref} />. React calls it with the element when it mounts and with null when it unmounts.requestFocus() calls element.focus() right away.ref next receives an element, focus it then.{ select: true }: after focusing, call element.select() if the element has a select method (inputs and textareas). Other elements are only focused, without throwing.ref and requestFocus keep the same identity across renders. (A new callback ref on every render makes React detach and re-attach it on every render.)function FileRow({ name, onRename }) {
const [editing, setEditing] = useState(false);
const { ref, requestFocus } = useFocusRequest();
const startEditing = () => {
setEditing(true);
requestFocus({ select: true }); // the input does not exist yet
};
return editing
? <input ref={ref} defaultValue={name} onBlur={(e) => { onRename(e.target.value); setEditing(false); }} />
: <button onClick={startEditing}>{name}</button>;
}
// Click "report.pdf": the input mounts, gets focus, and "report.pdf" is selected.
ref to an input, a textarea or a div. State changes and calls to requestFocus happen inside ReactDOM.flushSync.HTMLElement.prototype.focus and the select methods of inputs and textareas with recorders, and check which elements were focused and selected, in which order.Object.assign(window, { useFocusRequest }); below “Do not edit below this line”. The tests use it to call your hook.