forwardRef lets a component receive a parent’s ref and attach it to an element inside its render output. A labeled input can expose its underlying HTML input so a login form can focus the username field on load. This is a version-specific pattern: in React 19, a function component can accept ref as a regular prop instead. section 5.3.8
Type and forward an input ref
Define InputProps with a label and ComponentPropsWithoutRef<"input">. Then wrap the component: forwardRef<HTMLInputElement, InputProps>(function Input({ label, ...rest }, ref) { return <label><span>{label}</span><input ref={ref} {...rest} /></label>; }). A parent can create useRef<HTMLInputElement>(null), pass it as <Input ref={username} label="Username" name="username" />, and call username.current?.focus() in an effect. section 5.3.8
Specify the element type rather than relying on inference: an untyped forwardRef ref defaults to an unknown element type, which TypeScript will not assign to an input. Typing the render function’s parameter as Ref<HTMLInputElement> is an alternative to supplying forwardRef<HTMLInputElement, InputProps>. section 5.3.8 section 5.4
Generic components have a separate type-preservation problem. Forwarding a ref to a paginable component’s section can cause its item type to become unknown, breaking the match between items and their renderer. For an occasional component, cast the result of forwardRef to a generic call signature that includes RefAttributes<HTMLElement>; for many such components, augment React’s forwardRef type definition. The cast works but is complex enough to warrant an explanatory comment. section 6.2.1
Type '({ item }: CardProps) => Element' is not assignable to type
'FC<PagenableItemProps<unknown>>'.
Types of parameters '__0' and 'props' are incompatible.
Type 'PagenableItemProps<unknown>' is not assignable to type
'CardProps'.
Types of property 'item' are incompatible.
Type 'unknown' is not assignable to type 'Employee'.
The renderer error shows the practical symptom of lost generic inference: its item is treated as unknown rather than the expected item type. section 6.2.1
