Lesson 6 of 8
forwardRef & Generic Components
`forwardRef` allows parent components to access the DOM element inside a child component. TypeScript requires specifying the ref type AND the props type when using `forwardRef`. Generic React components present a special challenge with TypeScript - the JSX parser sometimes struggles with `<T>` syntax.
forwardRef, Generic Components & Polymorphic Patterns
// ── forwardRef - pass ref through to DOM element ────────────
// React.forwardRef<RefType, PropsType>
const TextInput = React.forwardRef<HTMLInputElement, {
label: string;
value: string;
onChange: (v: string) => void;
placeholder?: string;
error?: string;
}>(({ label, value, onChange, placeholder, error }, ref) => (
<div className="field">
<label>{label}</label>
<input
ref={ref} // ✅ ref forwarded to input element
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder={placeholder}
aria-invalid={!!error}
/>
{error && <span className="error">{error}</span>}
</div>
));
TextInput.displayName = "TextInput"; // required for DevTools
// Usage:
const inputRef = React.useRef<HTMLInputElement>(null);
<TextInput
ref={inputRef}
label="Task title"
value={title}
onChange={setTitle}
/>
// ── Generic component - T extends constraint ──────────────────
// Note: TypeScript parses <T> as a JSX tag in .tsx files.
// Solution: add a trailing comma: <T,> or constrain: T extends object
interface SelectProps<T> {
options: T[];
value: T | null;
onChange: (value: T) => void;
getLabel: (item: T) => string;
getValue: (item: T) => string | number;
placeholder?: string;
}
// Trailing comma workaround for .tsx files:
function Select<T,>({ options, value, onChange, getLabel, getValue, placeholder }: SelectProps<T>): React.ReactElement {
const handleChange = (e: React.ChangeEvent<HTMLSelectElement>): void => {
const selected = options.find((o) => String(getValue(o)) === e.target.value);
if (selected !== undefined) onChange(selected);
};
return (
<select
value={value !== null ? String(getValue(value)) : ""}
onChange={handleChange}
>
{placeholder && <option value="">{placeholder}</option>}
{options.map((option) => (
<option key={String(getValue(option))} value={String(getValue(option))}>
{getLabel(option)}
</option>
))}
</select>
);
}
// Usage with Task priority:
<Select<Priority>
options={["low", "medium", "high", "critical"]}
value={selectedPriority}
onChange={setSelectedPriority}
getLabel={(p) => p.charAt(0).toUpperCase() + p.slice(1)}
getValue={(p) => p}
placeholder="Select priority"
/>Common Mistakes
- Forgetting `displayName` on forwardRef components - without it, React DevTools shows 'ForwardRef' instead of the component name. Always set `ComponentName.displayName = 'ComponentName'`.
- Using `<T>` without trailing comma in `.tsx` - TypeScript sees `<T>` as a JSX opening tag. Write `<T,>` or `<T extends object>` to tell the parser it's a type parameter.
- Making forwardRef work with generic components - `React.forwardRef` doesn't support generic components directly. For truly generic + forwardRef components, use a cast: `const TypedSelect = Select as <T>(props: SelectProps<T> & { ref?: Ref<HTMLSelectElement> }) => ReactElement`.
Tip
Tip
Practice forwardRef Generic Components in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for forwardRef & Generic Components
Practice Task
Note
Practice Task - (1) Write a working example of forwardRef Generic Components from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with forwardRef Generic Components is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.
Key Takeaways
- `forwardRef` allows parent components to access the DOM element inside a child component.
- Forgetting `displayName` on forwardRef components - without it, React DevTools shows 'ForwardRef' instead of the component name. Always set `ComponentName.displayName = 'ComponentName'`.
- Using `<T>` without trailing comma in `.tsx` - TypeScript sees `<T>` as a JSX opening tag. Write `<T,>` or `<T extends object>` to tell the parser it's a type parameter.
- Making forwardRef work with generic components - `React.forwardRef` doesn't support generic components directly. For truly generic + forwardRef components, use a cast: `const TypedSelect = Select as <T>(props: SelectProps<T> & { ref?: Ref<HTMLSelectElement> }) => ReactElement`.
Finished this lesson?