[Typescript + React] Tip: Use generics in React to make dynamic and flexible components
You can use generics in React to make incredibly dynamic, flexible components. Here, I make a Table component with a generic 'items' type.
interface TableProps<TItem> {
items: TItem[]
renderItem: (item: TItem) => React.ReactNode
}
export function Table<TItem>(props: TableProps<TItem>) {
return null
}
type TableItem = {id: number; name: string}
const Component = () => {
return (
<Table<TableItem>
items={[
{
id: 1,
name: 'Jon',
},
]}
renderItem={(item) => <div>{item.name}</div>}
></Table>
)
}