Skip to content

Commit 44f2a00

Browse files
committed
docs: add callback ref example for focusing input on mount
Adds a new recipe to the useRef reference page demonstrating how to focus an input element on mount using a callback ref (function ref) rather than a useRef object ref. This addresses the documented use case in issue #8718 where users want to focus an element automatically without needing a button click, and where useCallback ensures the ref callback is stable across renders. Closes #8718
1 parent 46a54e0 commit 44f2a00

1 file changed

Lines changed: 32 additions & 0 deletions

File tree

‎src/content/reference/react/useRef.md‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,38 @@ export default function Form() {
300300
301301
<Solution />
302302
303+
#### Focusing an input using a callback ref {/*focusing-an-input-using-a-callback-ref*/}
304+
305+
Instead of a ref object, you can pass a **callback function** to the `ref` attribute. React will call your callback with the DOM node when it mounts, and with `null` when it unmounts. This is useful when you need to focus the element immediately on mount without a button click.
306+
307+
<Sandpack>
308+
309+
```js
310+
import { useCallback } from 'react';
311+
312+
export default function Form() {
313+
const inputRef = useCallback((node) => {
314+
if (node !== null) {
315+
node.focus();
316+
}
317+
}, []);
318+
319+
return (
320+
<>
321+
<label>
322+
Name:{' '}
323+
<input ref={inputRef} />
324+
</label>
325+
<p>The input above is focused automatically on mount.</p>
326+
</>
327+
);
328+
}
329+
```
330+
331+
</Sandpack>
332+
333+
<Solution />
334+
303335
#### Scrolling an image into view {/*scrolling-an-image-into-view*/}
304336
305337
In this example, clicking the button will scroll an image into view. It uses a ref to the list DOM node, and then calls DOM [`querySelectorAll`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll) API to find the image we want to scroll to.

0 commit comments

Comments
 (0)