Want to skip to the implementation? Check out these examples:
Column Faceting is a feature that allows you to generate lists of values for a given column from that column's data. For example, a list of unique values in a column can be generated from all rows in that column to be used as search suggestions in an autocomplete filter component. Or, a tuple of minimum and maximum values can be generated from a column of numbers to be used as a range for a range slider filter component.
In order to use any of the column faceting features, you must include the appropriate row models in your table options.
//only import the row models you needimport { getCoreRowModel, getFacetedRowModel, getFacetedMinMaxValues, //depends on getFacetedRowModel getFacetedUniqueValues, //depends on getFacetedRowModel}//...const table = useReactTable({ columns, data, getCoreRowModel: getCoreRowModel(), getFacetedRowModel: getFacetedRowModel(), //if you need a list of values for a column (other faceted row models depend on this one) getFacetedMinMaxValues: getFacetedMinMaxValues(), //if you need min/max values getFacetedUniqueValues: getFacetedUniqueValues(), //if you need a list of unique values //...})
First, you must include the getFacetedRowModel
row model. This row model will generate a list of values for a given column. If you need a list of unique values, include the getFacetedUniqueValues
row model. If you need a tuple of minimum and maximum values, include the getFacetedMinMaxValues
row model.
Once you have included the appropriate row models in your table options, you will be able to use the faceting column instance APIs to access the lists of values generated by the faceted row models.
// list of unique values for autocomplete filterconst autoCompleteSuggestions = Array.from(column.getFacetedUniqueValues().keys()) .sort() .slice(0, 5000);
// tuple of min and max values for range filterconst [min, max] = column.getFacetedMinMaxValues() ?? [0, 1];
If instead of using the built-in client-side faceting features, you can implement your own faceting logic on the server-side and pass the faceted values to the client-side. You can use the getFacetedUniqueValues
and getFacetedMinMaxValues
table options to resolve the faceted values from the server-side.
const facetingQuery = useQuery( //...)
const table = useReactTable({ columns, data, getCoreRowModel: getCoreRowModel(), getFacetedRowModel: getFacetedRowModel(), getFacetedUniqueValues: (table, columnId) => { const uniqueValueMap = new Map<string, number>(); //... return uniqueValueMap; }, getFacetedMinMaxValues: (table, columnId) => { //... return [min, max]; }, //...})
Alternatively, you don't have to put any of your faceting logic through the TanStack Table APIs at all. Just fetch your lists and pass them to your filter components directly.
Your weekly dose of JavaScript news. Delivered every Monday to over 100,000 devs, for free.