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

React.ComponentPropsWithRef vs React.forwardRef

I am trying to understand why we need to use React.forwardRef.

I can define props as React.ComponentPropsWithRef<‘input’> and pass a ref to the component.

Please help me understand what is wrong with doing this.

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

Thank you.

type TextboxProps = React.ComponentPropsWithRef<'input'>;

const Textbox = (props: TextboxProps): ReactElement | null => {
    return (
        <input
            type='number'
            value={props.value}
            onChange={props.onChange}
            ref={props.ref}
        />

    );
};

export { Textbox };

>Solution :

React.ComponentPropsWithRef only sets the type of the props of the component for the ref property to exist (as well as the other native attributes of the underlying element). However, without using React.forwardRef, passing the ref prop has no effect. ref.current will always be whatever initial value was passed to useRef.

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