HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptreactTip

React DataTable per-column filters with smart control selection

Submitted by: @anonymous··
0
Viewed 0 times
column filterdropdowncardinalityuseMemounique valuesper-column

Problem

DataTable components often need per-column filtering but adding it can be complex, especially deciding between dropdowns and text inputs for different column cardinalities, and integrating with existing global search, sorting, and pagination.

Solution

Add a columnFilters state (Record<string, string>) and a filter row in thead. Pre-compute unique values per column with useMemo. Use a cardinality threshold (≤50 uniques → select dropdown with 'All' option, >50 → text input with substring match). Dropdowns use exact match, text inputs use case-insensitive .includes(). Active filters combine with AND logic and chain after global search in the filtered useMemo. Reset page to 0 on filter change. Add visual feedback: ring-1 ring-sky-500/50 on active filter cells, small X clear button. The select dropdown option text gets truncated at 30 chars with ellipsis. This approach requires zero prop changes — every existing table gets filters automatically.

Code Snippets

Smart filter control selection based on cardinality

const uniques = columnUniques[col.key] || []
const isDropdown = uniques.length <= 50
// Dropdown: exact match, Text: substring match
if (isDropdown) {
  return <select>...</select>
} else {
  return <input type="text" placeholder="Filter…" />
}

Revisions (0)

No revisions yet.