Remove forwardRef references from useRef and Manipulating the DOM with Refs pages#7364
Conversation
|
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
Size changesDetails📦 Next.js Bundle Analysis for react-devThis analysis was generated by the Next.js Bundle Analysis action. 🤖 This PR introduced no changes to the JavaScript bundle! 🙌 |
| </Pitfall> | ||
|
|
||
| However, if you try to put a ref on **your own** component, like `<MyInput />`, by default you will get `null`. Here is an example demonstrating it. Notice how clicking the button **does not** focus the input: | ||
| When you put a ref on a built-in component that outputs a browser element like `<input />`, React will set that ref's `current` property to the corresponding DOM node (such as the actual `<input />` in the browser). |
There was a problem hiding this comment.
This is confusing. You need to walk through these stages:
- Passing a ref to
<input> - Creating your own component — it doesn't work anymore
- Fixing it by spreading props
Spreading props isn't a default thing people would reach for.
The paragraph above doesn't match the code below because the code below introduces spreading.
There was a problem hiding this comment.
Actually it might be better to remove spreading from examples below and just do ref={ref} so that it's obvious it works like any other prop
| import { useRef } from 'react'; | ||
|
|
||
| const MyInput = forwardRef((props, ref) => { | ||
| const MyInput = (props, ref) => { |
There was a problem hiding this comment.
Ref is a prop now, so it won't be a second argument. I'd suggest to directly pass it as a prop in this example and remove spreading to make the pattern very clear
|
|
||
| ## Troubleshooting {/*troubleshooting*/} | ||
|
|
||
| ### I can't get a ref to a custom component {/*i-cant-get-a-ref-to-a-custom-component*/} |
There was a problem hiding this comment.
This is still a problem. You'll just get a ref with undefined current value and no warning. We need to change the wording of this but the problem is real and needs to be described.
gaearon
left a comment
There was a problem hiding this comment.
see above:
- let's fix the examples to show passing
refdirectly without spreading - fix code example that has second argument, it's wrong
- keep the troubleshooting section but reword to match the new problem
74581f3 to
5083ad6
Compare
5083ad6 to
649211b
Compare
Fixed! |
Update the "useRef" and "Manipulating the DOM with Refs" pages to no longer use forwardRef since its no longer needed in React 19