TypeScript Course
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?

Flash Cards

Question

Why the trailing comma <T,> in .tsx files?

Click to reveal answer
Answer

Because TSX files compile JSX tags. If you write `const Comp = <T>() => {}`, the compiler gets confused and thinks `<T>` is the start of an HTML tag like `<div>`! Adding the comma `<T,>` breaks the ambiguity and proves it's a TypeScript generic.

Question

Can it extend a base type?

Click to reveal answer
Answer

Yes! Just like generic functions, you can constrain it. `<T extends { id: number }>` ensures that whatever data is passed into your Table component at least has an ID for React keys.