Using Generics with Components 11 exercises
solution

Converting a Class Component to be Generic

Like before, we'll bring TRow into TableProps:


interface TableProps<TRow> {
rows: TRow[];
renderRow: (row: TRow) => ReactNode;
}

Then we'll add TRow to the Table component:


// Error on TRow!
export class Table extends React.Component<TableProps<TRow>> {

Loading solution

Transcript

00:00 Okay. So we know TableProps has to be pretty similar to what we saw before. So let's add T row back in and put in T row here too. Now, we're having exactly the same issues we had before. TableProps T row requires a type argument. So let's put T row in there for now,

00:18 but we cannot find name T row. So where on this line do we instantiate T row? Well, the key is to put it just next to this table here. So table T row extends React component TableProps T row. This again works just beautifully.

00:38 We've got our table here, which has got T row in the generic slot there. Hover over rows, we can see this ID number, name, string, beautiful. That's really working nicely, and we've got this inference all working too. So these props can be like, it doesn't matter whether you're using

00:58 functional components or class components, they can work just the same. In fact, generic classes actually have a lot of different applications too, outside of even React. So generic classes, they can be used to represent lots and lots of different dynamic data structures. Very, very cool setup. But this is how you get generics working with class components.