Applying Generics to Components
Now we'll move to to applying what we've learned about functions and type helpers to components.
Consider this Table
component:
interface TableProps { rows: any[]; renderRow: (row: any) => React.ReactNode;}export const Table = (props: TableProps) => { return ( <table>
Transcript
00:00 Now, we're going to apply what we've learned with functions, with type helpers onto components. We have our table here, and a table is basically going to take in some rows and then a function to render that row into a React node. Here inside the table components, we have our rows being mapped over,
00:19 and then render row is being called on each one. Basically, put it inside a TR, which is going to render out all of the cells in that row. We have here in this version, we're passing in the data and we have our row here, and then we're passing in a TD with row.name.
00:37 Great. We'll end up with a table with just one row with name John, but this means we can reuse the table with different types of data and pass it different things to render different types of tables. Very, very common pattern. There's an issue though. Our render row function, the row here is typed as any,
00:56 even though we know the type of the data that's passing in here. This is bad because it means that we can access properties like row does not exist without getting proper warnings here. Dangerous, dangerous, dangerous. What we want to do is we definitely want to turn this into a generic type,
01:15 because we probably know that rows needs to be the same type here as here. Rows is going to need to be the same type as render row, and then we need to somehow attach that so that the inference starts working on this table component here. That's given you, I think, all the information you need.
01:33 There are some little tricks that you might need to do to get this working in a .tsx file because elsewhere we've been working in .ts files. So bear that in mind, and I think that's it. Good luck.