TypeScript
/Advanced
React: Generic Components
Definition
Creating React components that use TypeScript Generics `<T>` to dynamically determine the type of their props based on the data passed in.
Explain Like I'm New
Imagine building a `<Table>` component. Sometimes you pass an array of `Users`, sometimes an array of `Products`. If you hardcode the Table to expect Users, it breaks for Products. If you use a Generic Component, the Table adapts its internal types perfectly to whatever Array you hand it.
Real World Example
A `<SelectDropdown>` component. If you pass an array of `User` objects to the `options` prop, the `onChange` callback will automatically know it should return a `User` object.
Common Use Cases
- •Tables
- •Dropdowns
- •Lists
- •Form wrappers
Interactive Example
import React from 'react'; // Define Generic Props interface ListProps<T> { items: T[]; // The render function takes one item of type T and returns a React Node renderItem: (item: T) => React.ReactNode; } // Generic Function Component // T is captured from the 'items' array passed by the user export function List<T>(props: ListProps<T>) { return ( <ul> {props.items.map((item, index) => ( <li key={index}>{props.renderItem(item)}</li> ))} </ul> ); } // USAGE: // The compiler sees we passed an array of Strings. // Therefore, 'item' in the renderItem function is 100% typed as a string! /* <List items={["Apple", "Banana", "Cherry"]} renderItem={(item) => <strong>{item.toUpperCase()}</strong>} /> */
Interview Questions
basic
- How do you declare a Generic on an arrow function component?
intermediate
- Why do you need a comma `<T,>` when writing generic arrow functions in `.tsx` files?
advanced
- Can a generic component extend a base type requirement?