Skip to content

Commit d8d6bd7

Browse files
committed
docs: explain focusing an input with a callback ref
1 parent 2e6dca1 commit d8d6bd7

1 file changed

Lines changed: 14 additions & 0 deletions

File tree

‎src/content/learn/manipulating-the-dom-with-refs.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,20 @@ To implement this:
8080
3. In the `handleClick` function, read the input DOM node from `inputRef.current` and call [`focus()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on it with `inputRef.current.focus()`.
8181
4. Pass the `handleClick` event handler to `<button>` with `onClick`.
8282

83+
You can also pass a callback function as a `ref`. React calls it with the DOM node when the input is added to the screen, so you can focus the input as soon as it appears:
84+
85+
```js
86+
function focusOnMount(node) {
87+
node?.focus();
88+
}
89+
90+
export default function Form() {
91+
return <input ref={focusOnMount} />;
92+
}
93+
```
94+
95+
For a plain input that should receive focus when the page loads, [`autoFocus`](https://developer.mozilla.org/docs/Web/HTML/Global_attributes/autofocus) is usually simpler. A callback ref is useful when you need to run other logic when React attaches the DOM node. Keep the callback stable (for example, by defining it outside your component) so it doesn't run again on every render.
96+
8397
While DOM manipulation is the most common use case for refs, the `useRef` Hook can be used for storing other things outside React, like timer IDs. Similarly to state, refs remain between renders. Refs are like state variables that don't trigger re-renders when you set them. Read about refs in [Referencing Values with Refs.](/learn/referencing-values-with-refs)
8498
8599
### Example: Scrolling to an element {/*example-scrolling-to-an-element*/}

0 commit comments

Comments
 (0)