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
Loading Code Playground...
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?