Part 08 / Topic 2 of 6
A ref as a DOM handle: auto-focusing a search box
ref={someRef} on a JSX element is a signal to React: once the real DOM node for this element exists, hand it to someRef.current. That handle is what lets code reach past JSX, which can only describe what to render, into the browser's own imperative API for things JSX has no prop for. examples/02_autofocus_search_box.jsx's RestaurantSearchBox wants the search input focused the instant the screen appears, with no click or tab from the shopper:
// examples/02_autofocus_search_box.jsx
export function RestaurantSearchBox() {
const inputRef = useRef(null);
useEffect(() => {
// Runs once, right after the first render - the <input> DOM node
// already exists by then, so .focus() has something real to call.
inputRef.current.focus();
}, []);
return <input ref={inputRef} type="text" placeholder="Search restaurants near you" />;
}
The ref is seeded null because on the very first render, before React has committed anything to the screen, there is no DOM node yet to point at - only after commit does React fill it in, which is exactly why the .focus() call belongs inside an effect (runs after commit, Part 6), never directly in the render body. Rendering RestaurantSearchBox really leaves the input focused with no simulated click (examples/02_autofocus_search_box.test.jsx); the sibling RestaurantSearchBoxNoAutofocus, identical markup with no ref or effect, really is not focused after the same render - proving the behavior comes from this component, not from jsdom giving every input focus for free.
Done here? The practice set for Part 8 — including the solutions — is on the part page.