13

Why can't you pass a ref to a functional component in react?

What is different in function components compared to class components that you can't pass a ref to it?

Why is that not possible?

Notes: I'm making this question, because I always saw explanations about how to use ref with functional components, and that you need to use fowardRef, but no one explained how react handles functional components making it not possible to pass a ref to it, it's always explained how to do it, but never why you need to do it.

user31782
  • 7,087
  • 14
  • 68
  • 143
Vencovsky
  • 28,550
  • 17
  • 109
  • 176

2 Answers2

6

There are two aspects:

  • Function components don't have ref attribute because they don’t have instances like class components. Therefore you must FORWARD THE REF to any other element within it.
  • You can't use the ref prop as it reserved.

You can, however, use another prop name like innerRef and use if for forwarding.

Check a more detailed answer with examples: Why, exactly, do we need React.forwardRef?.

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
  • 1
    The "more detailed answer" this answerer linked to contains comments from THIS ASKER, requesting to understand WHY this is the case. And instead of answering this question here, the answerer regurgitated their explanation that it is not possible and then linked back to the question where the answerer encouraged the asker to ask this question somewhere else. I STILL don't understand WHY ref can't be passed to a function component. – Christopher Meyers Apr 29 '21 at 22:43
  • 1
    Yes the original question was asked in the comments, but you suggested it should be asked separately, presumably because you felt it was a different question with a different answer. But you did not provide a different answer here. You provided a shorter version of the same answer. The question here is WHY was the decision made to not allow ref as a prop. And your answer simply states that it won’t work. I will not be asking a separate question, as this question deserves an appropriate answer – Christopher Meyers May 01 '21 at 15:23
  • 1
    It would be helpful to understand the reason behind the decision, instead of the technical reason it can’t be done. – Christopher Meyers May 01 '21 at 15:33
  • @ChristopherMeyers "The question here is WHY was the decision made to not allow ref as a prop" are you asking, why the ref prop is preserved in function components? – Dennis Vash May 01 '21 at 17:18
2

I search on google with the same question: Why cannot pass ref like a props in React? And i find out the answer at React documentation:

There is one caveat to the above example: refs will not get passed through. That’s because ref is not a prop. Like key, it’s handled differently by React. If you add a ref to a HOC, the ref will refer to the outermost container component, not the wrapped component.

https://reactjs.org/docs/forwarding-refs.html

I hope that can give you a safisfactory answer!