Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Difference between forwardRef and ComponentPropsWithRef

I am trying to add ref to my custom function component. What is the difference between forwardRef and ComponentPropsWithRef?

const MyComponent = (ref) => { return <div ref={ref}>Some text</div> }

I have tried to use ComponentPropsWithRef but it doesn’t add ref at all

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

ref.current without React.forwardRef will always be whatever initial value was passed to useRef and won’t change.
React.ComponentPropsWithRef only adds ref property to the props of the component.
The solution might be const MyComponent= forwardRef<HTMLDivElement, MyComponentProps>((ref, props) => {return <div ref={ref}>Some text</div>})

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading