You might be used to using generics with functions but you can also use them with react components.
So here this Table component takes in an array of items which I've currently typed as just id: string and then it also takes a function to render the item which says item: {id: string}
interface TableProps {
items: { id: string }[]
renderItem: (item: { id: string }) => React.ReactNode
}
export const Table = (props: TableProps) => {
return null
}
What you want here is to be able to pass in any items and for that id string to then propagate through to the renderItem. You might try the following, using TItem, but this actually isn't valid.
export const Table = <TItem>(props: TableProps) => {
return null
}
What you need to do instead is you need to turn this Table into a standard function.
export function Table<TItem>(props: TableProps) {
return null
}
We need to make TableProps generic as well with TItem. Remember to use TItem in the items array and the renderItem function.
interface TableProps<TItem> {
items: TItem[]
renderItem: (item: TItem) => React.ReactNode
}
export function Table<TItem>(props: TableProps<TItem>) {
return null
}
And now anything we put in the Component props items will be propagated through to our item because it's generic.
If we ever want to pass the generic manually we specificy it with our Table instance. Now the example below will error out since id should be a number not a string.
const Component = () => {
return (
<Table<{ id: number }>
items={[{ id: "1", name: "Matt" }]}
renderItem={(item) => <div>{item.id}</div>}
></Table>
)
}
So it's a funny syntax and not a lot of people know about it. I kind of stumbled on it by accident and every time. But, every time I use it I think, "wow that's pretty cool!"
0 Comments
Log in to join the conversation.No comments yet. Be the first to share your thoughts.