Typing forwardRef for Ref-Forwarding Components
What you'll learn: How to properly type React components that forward refs while preserving full type safety for both props and the ref itself.
The Problem forwardRef Solves
React components don't receive refs as regular props—they require forwardRef to explicitly pass refs to DOM elements or child components. TypeScript needs to know both the ref's target type and the component's prop types.
Generic Signatures for forwardRef
The forwardRef function accepts two generic type parameters:
forwardRef<RefType, PropsType>(component)
RefType is what the ref points to (usually an HTMLElement), and PropsType defines the component's props.
Basic Pattern
interface ButtonProps {
label: string;
variant?: 'primary' | 'secondary';
}
const FancyButton = forwardRef<HTMLButtonElement, ButtonProps>(
(props, ref) => {
return (
<button ref={ref} className={props.variant}>
{props.label}
</button>
);
}
);
Now ref is typed as ForwardedRef<HTMLButtonElement>, props are fully typed with autocomplete, and parent components get type-checking when using refs.
With Children
interface CardProps {
title: string;
children: ReactNode;
}
const Card = forwardRef<HTMLDivElement, CardProps>(
({ title, children }, ref) => (
<div ref={ref}>
<h2>{title}</h2>
{children}
</div>
)
);
Why This Matters
Without proper generic signatures, you lose prop autocomplete or get any-typed refs. The two-parameter generic keeps both your props interface and ref target type explicit and safe.
Key Takeaway: Use forwardRef with proper generic signatures—forwardRef<RefElementType, PropsType>—to maintain full type safety for both the forwarded ref and component props simultaneously.