Sub topic 15
Typing components that forward refs
This chapter assumes you know how useRef works in a TSX project, how to type props, and how ComponentPropsWithoutRef extends native element props. It also assumes you can read a generic type parameter. The examples target React 18 types and note where React 19 differs.
Why refs need special handling
A ref is not an ordinary prop. React removes it from the props object before it calls a function component (in React 18 and earlier). If a parent writes <TextInput ref={inputRef} />, the component never sees ref in its props. The component has to opt in with forwardRef, which passes the ref as a second argument.
Typing this correctly means answering two questions:
- What kind of object does the parent get back in
ref.current? - What props does the component accept, not counting
ref?
The forwardRef signature
forwardRef takes two type parameters, and the order is easy to get backwards:
import { forwardRef, type ComponentPropsWithoutRef } from "react";
export const TextInput = forwardRef<
HTMLInputElement,
ComponentPropsWithoutRef<"input">
>(function TextInput(props, ref) {
return <input ref={ref} {...props} />;
});- The first parameter,
HTMLInputElement, is the type of the value the ref will hold. It is the ref type. - The second parameter,
ComponentPropsWithoutRef<"input">, is the props type.
If you swap them, TypeScript usually reports errors inside the function body, because props becomes an element type and ref becomes a props type. The error messages mention missing properties, not "wrong order", so check the order first.
The inner function is named TextInput. This is deliberate. React DevTools and error messages use the function name, so an anonymous arrow function would show up as ForwardRef. If you prefer an arrow function, set TextInput.displayName = "TextInput".
Why `WithoutRef`
Use ComponentPropsWithoutRef<"input"> for the props type. The plain ComponentProps<"input"> and ComponentPropsWithRef<"input"> include a ref property. forwardRef already adds its own ref to the resulting component type. If your props type also contains ref, the two definitions collide, and you can end up with a ref type that accepts legacy string refs or mismatched element types.
| Type | Contains `ref`? | Use it for |
|---|---|---|
| `ComponentPropsWithoutRef<"input">` | No | Props type passed to `forwardRef` |
| `ComponentPropsWithRef<"input">` | Yes | Components that take `ref` as a normal prop (React 19) |
| `ComponentProps<"input">` | Yes | Quick typing when you do not forward refs |
Using the typed ref from a parent
The parent creates the ref with the same element type. Because a DOM ref is null until the component mounts, you must handle null:
import { useRef } from "react";
import { TextInput } from "./TextInput";
export function SearchBar() {
const inputRef = useRef<HTMLInputElement>(null);
return (
<div>
<TextInput ref={inputRef} placeholder="Search" />
<button onClick={() => inputRef.current?.focus()}>Focus</button>
</div>
);
}If you write useRef<HTMLDivElement>(null) and pass it to TextInput, the compiler rejects it. The ref type no longer matches, and the error names both element types. This is the main benefit of typing the forwarded ref: a parent cannot attach a ref for the wrong element.
Forwarding to a different element than the root
You can forward the ref to any element inside the component, not only the root. The ref type must match the element that receives it:
import { forwardRef, type ComponentPropsWithoutRef } from "react";
interface FieldProps extends ComponentPropsWithoutRef<"input"> {
label: string;
}
export const Field = forwardRef<HTMLInputElement, FieldProps>(
function Field({ label, id, ...rest }, ref) {
return (
<div>
<label htmlFor={id}>{label}</label>
<input id={id} ref={ref} {...rest} />
</div>
);
}
);The parent gets an HTMLInputElement, not the wrapping div. Document this in a comment or the prop names, because nothing in the type tells a reader which inner element is exposed beyond the element type.
Exposing a custom handle with useImperativeHandle
Sometimes you do not want to expose the whole DOM node. A narrower API is safer, because the parent cannot change attributes or remove the node. In that case, define a handle interface and use it as the ref type:
import { forwardRef, useImperativeHandle, useRef } from "react";
export interface FancyInputHandle {
focus(): void;
clear(): void;
}
interface FancyInputProps {
label: string;
}
export const FancyInput = forwardRef<FancyInputHandle, FancyInputProps>(
function FancyInput({ label }, ref) {
const inputRef = useRef<HTMLInputElement>(null);
useImperativeHandle(
ref,
() => ({
focus() {
inputRef.current?.focus();
},
clear() {
if (inputRef.current) inputRef.current.value = "";
},
}),
[]
);
return (
<label>
{label}
<input ref={inputRef} />
</label>
);
}
);The factory function passed to useImperativeHandle must return a value assignable to FancyInputHandle. If you add a method to the interface and forget to implement it, the compiler reports the error here. The parent uses it like this:
import { useRef } from "react";
import { FancyInput, type FancyInputHandle } from "./FancyInput";
export function Form() {
const handle = useRef<FancyInputHandle>(null);
return (
<>
<FancyInput ref={handle} label="Name" />
<button onClick={() => handle.current?.clear()}>Reset</button>
</>
);
}Export the handle interface. Parents need it to type their own useRef.
Generic components lose their type parameter
forwardRef returns a non-generic component type. If you wrap a generic component directly, TypeScript infers T as unknown for every use. The common workaround is to write the inner function separately and cast the result:
import { forwardRef, type ForwardedRef, type Ref } from "react";
interface SelectProps<T> {
options: T[];
getLabel: (option: T) => string;
onPick: (option: T) => void;
}
function SelectInner<T>(
{ options, getLabel, onPick }: SelectProps<T>,
ref: ForwardedRef<HTMLSelectElement>
) {
return (
<select ref={ref} onChange={(e) => onPick(options[e.target.selectedIndex])}>
{options.map((option, i) => (
<option key={i}>{getLabel(option)}</option>
))}
</select>
);
}
export const Select = forwardRef(SelectInner) as <T>(
props: SelectProps<T> & { ref?: Ref<HTMLSelectElement> }
) => ReturnType<typeof SelectInner>;The cast is the cost. TypeScript trusts you, so a mistake in the cast signature will not be caught. Keep the cast right next to the function it describes, and keep the props type in one named interface so the two cannot drift apart. ForwardedRef<T> is the type of the second argument of the render function. It is ((instance: T | null) => void) | MutableRefObject<T | null> | null, which is why you pass it straight to a ref attribute and do not read .current from it.
React 19: ref as a regular prop
In React 19, function components receive ref as an ordinary prop, and forwardRef is no longer needed for new code. The typing moves to the props:
import type { ComponentPropsWithRef } from "react";
export function TextInput(props: ComponentPropsWithRef<"input">) {
return <input {...props} />;
}Here ComponentPropsWithRef<"input"> is the correct choice, because ref is now part of the props. This only type-checks against the React 19 versions of @types/react. On React 18 types, a function component cannot receive ref this way. Check your installed version before choosing a style, and keep one style per codebase.
Common errors
- "Property 'ref' does not exist on type IntrinsicAttributes": the component is a plain function on React 18 types. Wrap it in
forwardRef. - "Type 'RefObject<HTMLDivElement>' is not assignable to type 'Ref<HTMLInputElement>'": the parent's
useRefelement type does not match the forwarded element. ref.currentisundefinedin the parent: the child never attachedrefto an element, or you forgot to spread it. The compiler cannot detect this, so test it.ForwardRefin DevTools: the render function is anonymous. Name it or setdisplayName.- Duplicate
refin props: you usedComponentProps<"input">instead ofComponentPropsWithoutRef<"input">.
Exercise
A teammate writes forwardRef<ComponentPropsWithoutRef<"button">, HTMLButtonElement>(...). The code compiles in the parent but fails inside the render function. What is wrong, and what is the fix?
Show answer
The type parameters are in the wrong order. forwardRef expects the ref type first and the props type second. Swap them: forwardRef<HTMLButtonElement, ComponentPropsWithoutRef<"button">>(...). The render function then gets props as button props and ref as a ref to an HTMLButtonElement.
Exercise
You build Modal with forwardRef<ModalHandle, ModalProps>, where ModalHandle has open() and close(). How does a parent type its ref, and why must it check current before calling open()?
Show answer
The parent writes const modal = useRef<ModalHandle>(null) and imports ModalHandle from the component's module, so the interface must be exported. modal.current is null until the component mounts, so the call should be modal.current?.open(). In strict mode the compiler rejects an unchecked call.