Generic Table component with React and Typescript
--
Display any kind of data using the same table component while enjoying the benefits of typescript features.
A very common use case is to be able to list multiple types of data using tables. This happens quite frequently in dashboards for instance.
For example, an e-commerce dashboard might want to display a table to list the items they have in their stock, and in another table, they want to display the list of client addresses.
When using React with Typescript we want to explore as much as possible the typing benefits it brings to us by creating a consistent component API. Which is both pleasant to work with and also powerful.
We’ll illustrate this by creating a simple Table component which provides us the basic functionality to have a generic table which deals primarily with 3 things:
- Displaying primitives types (string, numbers, and booleans) out of the box.
- Table Headers
- Custom rendering of data for advanced types, such as Object or Array.
Displaying primitive types out of the box
Let’s break down what’s happening here:
- We defined the helpers
objectValues
which provides us a better way to get the object values with the correct typing. - Defined a type guard
isPrimitive
which basically defines which types we are going to print out of the box. - Defined the initial stricture of our Table component. Which simply map over the
items
prop provided, creating a row for each, and inside each row we render each object entry as a different data cell. Notice that we will only print something if the item entry passes the testisPrimitive(entry)
.
So far, so good. One thing to notice here is the usage of the generic type T. In which we have added a constraint by doing T extends MinTableItem
. This constraint requires that every item data has to have at least one property called id
which can be a PrimitiveType
.