React Component Typing
Building bulletproof React components.
Typing Props
In modern React, we use TypeScript interface or type definitions to strictly define what props a component accepts.
But the real magic happens when you use **Generics** to create polymorphic components (like a Table that can render *any* data type while keeping strict type safety).
The Reusability Problem
If you build a <Table> component typed specifically for a User[], you can't reuse it for a Product[]. If you type the data as any[], you lose all autocompletion when trying to render a row.
By passing a type variable <T> to the component props, the Table dynamically molds itself to whatever array you pass into it.
Syntax
tsx
import { ReactNode } from "react";
interface TableProps<T> {
data: T[];
renderRow: (item: T) => ReactNode;
}
// Notice the trailing comma <T,> - it prevents the
// JSX parser from confusing it with an HTML tag!
export function Table<T,>({ data, renderRow }: TableProps<T>) {
return (
<div>{data.map((item, i) => renderRow(item))}</div>
);
}
Try it
Pass different data arrays to the generic <Table> component and watch how TypeScript instantly infers the correct types for the renderRow callback prop.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Use Generics
<T>to create highly reusable React components. - A generic
<Table data={users}>will automatically infer thatTisUser. - In
.tsxarrow functions, use<T,>to avoid JSX parsing errors. - Stop using
React.FC—type your function parameters directly.
Done with this concept?
Mark it complete to track your progress. No login needed.