Do you want to request a feature or report a bug?
feature
What is the current behavior?
Today we use forwardRef as a HOC around functional component, like this:
const MyComponent = React.forwardRef((props, ref) => {
return (<div {...props} ref={ref}>Some text</div>);
});
MyComponent.displayName = 'MyComponent';
What is the expected behavior?
Is it possible to use hooks to forward ref? For example, something like this:
const MyComponent = (props) => {
// will return ref that was passed from parent component
const forwardedRef = useForwardredRef();
return (<div {...props} ref={forwardedRef}>Some text</div>);
}
With this approach we don't need to manually set displayName all the time, also this would be great for libraries, as you still export same component, not a forwardRef HOC.
Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?
React 16.8 and upper
not a forwardRef HOC.
It's not really a HOC though. Even better it doesn't create an additional nesting in dev tools if you put all your hooks inside the render function of forwardRef.
Adding a useForwardRef hook would probably break https://overreacted.io/why-isnt-x-a-hook/.
The good news is that ref forwarding will become significantly handier once reactjs/rfcs#107 is accepted.
With this approach we don't need to manually set displayName all the time
const Component = React.forwardRef(function MyComponent() {});
will already create a display name in devtools for you : ForwardRef(MyComponent);
The plan is to eventually get rid of the need for forwardRef altogether by putting it back into props.
https://github.com/reactjs/rfcs/blob/createlement-rfc/text/0000-create-element-changes.md#move-ref-extraction-to-class-render-time-and-forwardref-render-time
We're not quite there yet.
Adding a useForwardRef hook would probably break https://overreacted.io/why-isnt-x-a-hook/.
I guess it is somewhat non-compositional because you can't pass the same ref to two things. Although it's not as bad as some other non-compositional Hooks.
The plan is to eventually get rid of the need for
forwardRefaltogether by putting it back intoprops.
Wow, that would make things much easier! Thanks for explanation!
Hi,
Any news about this eventual hook or rfc ?
Any updates on this issue?
Any updates?
Most helpful comment
The plan is to eventually get rid of the need for
forwardRefaltogether by putting it back intoprops.https://github.com/reactjs/rfcs/blob/createlement-rfc/text/0000-create-element-changes.md#move-ref-extraction-to-class-render-time-and-forwardref-render-time
We're not quite there yet.
I guess it is somewhat non-compositional because you can't pass the same ref to two things. Although it's not as bad as some other non-compositional Hooks.