Course contentsShow
← React
Lesson 2367 of 2,39651. TypeScript with React BasicsFree lesson

Refs in forwardRef Components

Type both the ref parameter and the component props when using forwardRef.

Refs in forwardRef Components

What you'll learn: How to properly type both the ref parameter and component props when using forwardRef in TypeScript.

When you use forwardRef, you're creating a component that accepts a ref from its parent and passes it down to a DOM element or child component. TypeScript needs explicit types for both the forwarded ref and the component's props to ensure type safety throughout this chain.

The Two-Part Type Annotation

forwardRef is a generic function that takes two type parameters:

  1. The ref type – what kind of element or component the ref points to (e.g., HTMLInputElement)
  2. The props type – the interface defining the component's props
import { forwardRef } from 'react';

interface CustomInputProps {
  label: string;
  placeholder?: string;
}

const CustomInput = forwardRef<HTMLInputElement, CustomInputProps>(
  (props, ref) => {
    return (
      <div>
        <label>{props.label}</label>
        <input ref={ref} placeholder={props.placeholder} />
      </div>
    );
  }
);

Why Both Types Matter

Think of it like a relay race: the ref is the baton being passed, and the props are the instructions for the runner. TypeScript needs to know what kind of baton (HTMLInputElement) and what instructions (CustomInputProps) are valid.

Without proper typing, you lose autocomplete on props and TypeScript won't catch errors if you pass the wrong ref type to the parent component.

Order Matters

The generic order is always <RefType, PropsType>, matching the order of the callback parameters (props, ref).

Key Takeaway: When using forwardRef, always provide both generic type parameters: the element type for the ref first, then your props interface second, ensuring full type safety for both the forwarded ref and component props.