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.

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.

Leave a Reply