You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/content/learn/manipulating-the-dom-with-refs.md
+9-7Lines changed: 9 additions & 7 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -360,7 +360,7 @@ export default function MyForm() {
360
360
constinputRef=useRef(null);
361
361
362
362
functionhandleClick() {
363
-
inputRef.current?.focus();
363
+
inputRef.current.focus();
364
364
}
365
365
366
366
return (
@@ -376,13 +376,15 @@ export default function MyForm() {
376
376
377
377
</Sandpack>
378
378
379
+
Instead, the application crashes because `inputRef.current` is `null`, due to `<MyInput />` not passing the `ref` prop down to one of its children.
380
+
379
381
This happens because by default React does not let a component access the DOM nodes of other components. Not even for its own children! This is intentional. Refs are an escape hatch that should be used sparingly. Manually manipulating _another_ component's DOM nodes makes your code even more fragile.
380
382
381
383
Instead, components that _want_ to expose their DOM nodes have to **opt in** to that behavior. A component can specify that it "forwards" its ref to one of its children by passing the `ref` prop down.
382
384
383
385
```js
384
-
functionMyInput({ ref, ...props }) {
385
-
return<input {...props} ref={ref} />;
386
+
functionMyInput({ ref }) {
387
+
return<input ref={ref} />;
386
388
}
387
389
```
388
390
@@ -398,8 +400,8 @@ Now clicking the button to focus the input works:
398
400
```js
399
401
import { useRef } from'react';
400
402
401
-
functionMyInput({ ref, ...props }) {
402
-
return<input {...props} ref={ref} />;
403
+
functionMyInput({ ref }) {
404
+
return<input ref={ref} />;
403
405
}
404
406
405
407
exportdefaultfunctionForm() {
@@ -435,15 +437,15 @@ In the above example, `MyInput` exposes the original DOM input element. This let
0 commit comments