TLDR: If you have null field data, you'll need to take an extra step to get an accurate column count in React Table.
React Table
I've been working with React Table v8, and it is very good!
It has allowed me to quickly create a very useful table for a large amount of data.
The only problem with this data: It has a lot of null values saved over approximately 15 years.
I implemented column filters like you see in this React Table example, but I noticed the item count shown in the placeholder text was off.
The code in the docs example giving the column item count for the filter input placeholder:
<DebouncedInput
// other attributes here
placeholder={`Search... (${column.getFacetedUniqueValues().size})`}
/>
getFacetedUniqueValues
returns a Map.
The number of items in a Map is retrieved from its size property.
The Column Item Count Fix
The above works great if your data has no null values OR you want to include those null values in your count.
In my implementation, I did not want to count those values.
To avoid including them in the item count, I switched from the above placeholder to what you see here:
<DebouncedInput
// other attributes here
placeholder={`Search... (${[...column.getFacetedUniqueValues()].filter(arr => arr[0]).length})`}
/>
Spreading the Map returned from column.getFacetedUniqueValues()
into a new array provides me with an array of arrays.
I filter that array to eliminate any null, empty or false values and finally, get the length value of the array.
You would want to handle this differently if you were filtering boolean or numerical data.
In this example, I'm filtering a text field and only looking for a truthy return in the filter method.
Now I have an accurate column item count that does not include any null or empty values.
Filtering by Null Values
In the end, my stakeholders wanted to be able to filter by the null values in their data.
To do this, you need to replace the null data in the React Table with something else.
You can do this in the accessor function as you create your columns.
Here is the part to add in your accessor function:
if (row[key] == null) return '✖'
This allows the table filter to use the ✖ value.
Note: the ✖ will show in the table instead of an empty cell, too.
This is what my stakeholders wanted. Your mileage may vary.
Let's Connect!
Hi, I'm Dave. I work as a full-time developer, instructor and creator.
If you enjoyed this article, you might enjoy my other content, too.
My Stuff: Courses, Cheat Sheets, Roadmaps
My Blog: davegray.codes
YouTube: @davegrayteachescode
GitHub: gitdagray
LinkedIn: /in/davidagray
Patreon: Join my Support Team!
Buy Me A Coffee: You will have my sincere gratitude
Thank you for joining me on this journey.
Dave
Top comments (0)