Library Utilities
Constants, filter and format helpers, filter functions, and layout helpers.
The lib/ folder holds the constants and helper functions the data table uses.
Constants
Section titled “Constants”Shared constants for join operators, filter operators, filter variants, and UI settings.
JOIN_OPERATORS
Section titled “JOIN_OPERATORS”How several filters combine.
| Constant | Value | Description |
|---|---|---|
AND |
"and" |
Logical AND (all filters must match) |
OR |
"or" |
Logical OR (any filter can match) |
MIXED |
"mixed" |
Mixed logic (combination of AND/OR) |
FILTER_OPERATORS
Section titled “FILTER_OPERATORS”How a filter compares values. Names follow SQL and PostgREST.
| Constant | Value | Description |
|---|---|---|
ILIKE |
"ilike" |
SQL ILIKE (Case-insensitive search) |
NOT_ILIKE |
"not.ilike" |
SQL NOT ILIKE |
EQ |
"eq" |
SQL EQUAL (=) |
NEQ |
"neq" |
SQL NOT EQUAL (!=) |
IN |
"in" |
SQL IN (one of) |
NOT_IN |
"not.in" |
SQL NOT IN (none of) |
EMPTY |
"empty" |
Value is null or empty string |
NOT_EMPTY |
"not.empty" |
Value is not null and not empty string |
LT |
"lt" |
SQL LESS THAN (<) |
LTE |
"lte" |
SQL LESS THAN OR EQUAL (<=) |
GT |
"gt" |
SQL GREATER THAN (>) |
GTE |
"gte" |
SQL GREATER THAN OR EQUAL (>=) |
BETWEEN |
"between" |
SQL BETWEEN (range) |
RELATIVE |
"relative" |
Relative date calculation (e.g., “today”) |
FILTER_VARIANTS
Section titled “FILTER_VARIANTS”Which UI control a filter uses.
| Constant | Value | Description |
|---|---|---|
TEXT |
"text" |
Standard text input |
NUMBER |
"number" |
Numeric input |
RANGE |
"range" |
Two-value range input |
DATE |
"date" |
Single date picker |
DATE_RANGE |
"dateRange" |
Date range picker |
SELECT |
"select" |
Single select dropdown |
MULTI_SELECT |
"multiSelect" |
Multi-select dropdown |
BOOLEAN |
"boolean" |
Checkbox or toggle |
DEFAULT_VALUES
Section titled “DEFAULT_VALUES”Global default values.
| Property | Value | Description |
|---|---|---|
JOIN_OPERATOR |
JOIN_OPERATORS.AND |
Default join operator |
PAGE_SIZE |
10 |
Default page size |
PAGE_INDEX |
0 |
Default page index |
UI_CONSTANTS
Section titled “UI_CONSTANTS”UI limits and settings.
| Property | Value | Description |
|---|---|---|
FILTER_ID_MAX_LENGTH |
100 |
Max characters allowed for a filter ID |
MAX_FILTER_DISPLAY_HEIGHT |
300 |
Default max height for scrollable filter popovers |
DEBOUNCE_DELAY |
300 |
Default debounce delay in milliseconds for search inputs |
KEYBOARD_SHORTCUTS
Section titled “KEYBOARD_SHORTCUTS”Default shortcut keys.
| Property | Value | Description |
|---|---|---|
FILTER_TOGGLE |
"f" |
Open/Toggle filter menu |
FILTER_REMOVE |
"f" |
Remove active filter (with Shift) |
ESCAPE |
"escape" |
Close active UI elements |
ENTER |
"enter" |
Confirm or submit active action |
BACKSPACE |
"backspace" |
Remove character or navigate back |
DELETE |
"delete" |
Item deletion |
Data Table Utilities
Section titled “Data Table Utilities”Helpers for filter operators and validation.
getFilterOperators
Section titled “getFilterOperators”Returns the operators a filter variant allows.
import { getFilterOperators } from "@/components/niko-table/lib/data-table"import { FILTER_VARIANTS } from "@/components/niko-table/lib/constants"
const textOperators = getFilterOperators(FILTER_VARIANTS.TEXT)// Returns: [{ label: "Contains", value: "ilike" }, ...]Parameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
filterVariant |
FilterVariant |
The filter variant type |
Returns
Section titled “Returns”Array of operator objects with label and value properties.
Type: Array<{ label: string; value: FilterOperator }>
getDefaultFilterOperator
Section titled “getDefaultFilterOperator”Returns the default operator for a filter variant.
import { getDefaultFilterOperator } from "@/components/niko-table/lib/data-table"import { FILTER_VARIANTS } from "@/components/niko-table/lib/constants"
const defaultOp = getDefaultFilterOperator(FILTER_VARIANTS.TEXT)// Returns: "ilike"Parameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
filterVariant |
FilterVariant |
The filter variant type |
Returns
Section titled “Returns”FilterOperator - The default operator for the variant.
getValidFilters
Section titled “getValidFilters”Removes invalid filters from an array.
import { getValidFilters } from "@/components/niko-table/lib/data-table"
const validFilters = getValidFilters(filters)// Returns: ExtendedColumnFilter<TData>[] with only valid filtersParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
filters |
ExtendedColumnFilter<TData>[] |
Array of filters to validate |
Returns
Section titled “Returns”ExtendedColumnFilter<TData>[] - Array containing only valid filters.
Format Utilities
Section titled “Format Utilities”Functions that format dates, labels, and query strings.
formatDate
Section titled “formatDate”Turns a date into readable text.
import { formatDate } from "@/components/niko-table/lib/format"
formatDate(new Date())// Returns: "January 1, 2024"
formatDate(new Date(), { month: "short", day: "numeric" })// Returns: "Jan 1"Parameters
Section titled “Parameters”| Name | Type | Default | Description |
|---|---|---|---|
date |
Date | string | number | undefined |
- | Date value to format |
opts |
Intl.DateTimeFormatOptions |
{} |
Formatting options |
Returns
Section titled “Returns”string - Formatted date string, or empty string if date is invalid.
formatLabel
Section titled “formatLabel”Turns a value into a readable label. It capitalizes each word and swaps hyphens and underscores for spaces.
import { formatLabel } from "@/components/niko-table/lib/format"
formatLabel("firstName") // "FirstName"formatLabel("first-name") // "First Name"formatLabel("first_name") // "First Name"formatLabel("true") // "Yes"formatLabel("false") // "No"Parameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
value |
string |
Value to format |
Returns
Section titled “Returns”string - Formatted label string.
daysAgo
Section titled “daysAgo”Returns the date N days before today.
import { daysAgo } from "@/components/niko-table/lib/format"
daysAgo(7) // 7 days agodaysAgo(30) // 30 days ago (1 month)daysAgo(365) // 365 days ago (1 year)Parameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
days |
number |
Number of days to subtract |
Returns
Section titled “Returns”Date - Date object representing the date N days ago.
formatQueryString
Section titled “formatQueryString”Turns URL query parameters into a readable query string for display.
import { formatQueryString } from "@/components/niko-table/lib/format"
const urlParams = { search: "i", globalFilter: { filters: [...], joinOperator: "mixed" } }const urlKeys = { search: "search", globalFilter: "global" }formatQueryString(urlParams, urlKeys)// Returns: "?search=i&global={"filters":[...], "joinOperator":"mixed"}"Parameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
urlParams |
Record<string, unknown> |
The parsed URL parameters object |
urlKeys |
Record<string, string> |
Mapping of parameter keys to URL query keys |
Returns
Section titled “Returns”string - Formatted query string (e.g., ?search=i&global={"filters":[...]}).
Table Features
Section titled “Table Features”In Table v8, useReactTable bundled every feature. In Table v9 you import only what you need.
- Same idea as the registry: mix and match
DataTable*components and install only the pieces you use. - Two layers: registry items do this for the UI. This file does it for the table engine.
A feature’s API exists on the table instance only once you register it.
- Passed for you:
DataTableRoothands this object touseTable. - Registration: decides whether the API exists.
- Feature detection and
enable*flags: decide when the behavior runs.
features
Section titled “features”import { features } from "@/components/niko-table/lib/data-table-features"
// DataTableRoot does this internally — you only need it for a custom table.const table = useTable({ features, data, columns })DataTableFeatures is the type of that object. Every DataTable* type alias is bound to it (DataTableInstance<TData> is Table<DataTableFeatures, TData>, and so on), so you rarely name it yourself.
createDataTableColumnHelper
Section titled “createDataTableColumnHelper”A TanStack Table v9 column helper with features already bound.
- Why: TanStack recommends
createColumnHelper()for static columns (typedgetValue()in cells). - Problem: the raw v9 helper needs the features generic passed by hand (
createColumnHelper<DataTableFeatures, TData>()). - Fix: this wraps it, the same way
DataTableColumnDef<TData>binds features.
import { createDataTableColumnHelper } from "@/components/niko-table/lib/data-table-features"
const columnHelper = createDataTableColumnHelper<Product>()
const columns = [ columnHelper.accessor("name", { header: "Name" }), columnHelper.accessor("price", { header: "Price", cell: ({ getValue }) => getValue().toFixed(2), // `getValue()` is `number` }), columnHelper.display({ id: "actions", cell: () => <button type="button">Edit</button>, }),]- Use the helper for typed
getValue()in cells. Put the results in aDataTableColumns<TData>array (whatDataTableRootaccepts). - Use a plain
DataTableColumnDef<TData>[]for dynamic columns and easy copy-paste. Examples still use this by default.
Trimming it down
Section titled “Trimming it down”The shipped file registers every feature the library can use, plus the row models they need:
- sorting, filtering, faceting, grouping, aggregation
- pagination, expanding, selection
- column visibility, ordering, pinning, sizing, resizing
You own the file after install. Delete the features and the built-in sortFns / aggregationFns your tables never use.
Watch out: removing a feature removes its API. Calling table.setGrouping() without columnGroupingFeature fails at runtime, not at build time.
Adding your own filter function
Section titled “Adding your own filter function”Register it under filterFns and reference it by name from a column:
export const features = tableFeatures({ // ... filterFns: { extended: extendedFilter, numberRange: numberRangeFilter, dateRange: dateRangeFilter, startsWith: (row, columnId, value: string) => String(row.getValue(columnId)).toLowerCase().startsWith(value.toLowerCase()), },})
const columns: DataTableColumnDef<Item>[] = [ { accessorKey: "name", filterFn: "startsWith" },]Filter Functions
Section titled “Filter Functions”Fast custom filter functions for TanStack Table.
This module has optimized filter functions for TanStack Table:
- Regex caching: caches compiled regex patterns for 70-90% faster filtering
- Operator support: all filter operators (ilike, eq, neq, in, between, etc.)
- Performance: LRU-style cache eviction prevents memory leaks
Performance Notes
Section titled “Performance Notes”Regex caching speeds up filtering:
- Without caching: 1,000 rows × 10 columns = 10,000 regex creations per search keystroke (~100-500ms)
- With caching: First search creates regex once, subsequent searches reuse cached regex (~5-20ms)
The cache holds at most 100 entries and evicts the oldest (LRU-like) to prevent memory leaks.
extendedFilter
Section titled “extendedFilter”A filter function that supports every operator (ilike, eq, neq, in, not_in, between, lt, gt, lte, gte, empty, not_empty). It is the default filterFn for columns with advanced filtering.
import { extendedFilter } from "@/components/niko-table/lib/filter-functions"
const columns = [ { accessorKey: "name", filterFn: extendedFilter, },]globalFilter
Section titled “globalFilter”A global filter that searches all visible columns. Works with debounced search input.
import { useTable } from "@tanstack/react-table"
import { features } from "@/components/niko-table/lib/data-table-features"import { globalFilter } from "@/components/niko-table/lib/filter-functions"
const table = useTable({ features, globalFilterFn: globalFilter,})numberRangeFilter
Section titled “numberRangeFilter”Filter for numeric range columns. Keeps rows whose value is between [min, max].
import { numberRangeFilter } from "@/components/niko-table/lib/filter-functions"
const columns = [ { accessorKey: "price", filterFn: numberRangeFilter, },]dateRangeFilter
Section titled “dateRangeFilter”Filter for date range columns. Keeps rows whose date is between a start and end date.
import { dateRangeFilter } from "@/components/niko-table/lib/filter-functions"
const columns = [ { accessorKey: "createdAt", filterFn: dateRangeFilter, },]createFilterValue
Section titled “createFilterValue”Builds a typed filter value from an ExtendedColumnFilter. The filter menu and inline filter use it inside.
import { createFilterValue } from "@/components/niko-table/lib/filter-functions"
const filterValue = createFilterValue(filter)processFiltersForLogic
Section titled “processFiltersForLogic”Decides where an array of ExtendedColumnFilter objects goes:
- Pure AND: goes to TanStack’s
columnFilters. - Any OR or mixed logic: goes in
globalFilter, because TanStack combines column filters with AND only.
import { processFiltersForLogic } from "@/components/niko-table/lib/data-table"
const { processedFilters, // filters with normalized joinOperator values hasOrFilters, // any rule joined with OR hasSameColumnFilters, // multiple rules target one column shouldUseGlobalFilter, // true → route via globalFilter, not columnFilters joinOperator, // "and" | "mixed"} = processFiltersForLogic(filters)Style Utilities
Section titled “Style Utilities”Helpers for styling table parts, mainly column pinning.
getCommonPinningStyles
Section titled “getCommonPinningStyles”Returns CSS styles for pinned columns (sticky position, z-index, shadows). DataTable components use it inside. You can use it in custom code.
import { getCommonPinningStyles } from "@/components/niko-table/lib/styles"
// In a custom header cellconst pinningStyles = getCommonPinningStyles(column, true)
// In a custom body cellconst pinningStyles = getCommonPinningStyles(column, false)Parameters
Section titled “Parameters”| Name | Type | Default | Description |
|---|---|---|---|
column |
DataTableColumn<TData> |
- | TanStack Table column instance |
isHeader |
boolean |
false |
Whether this is a header cell (sets top: 0 for vertical stickiness and z-index 20) |
Returns
Section titled “Returns”React.CSSProperties - CSS styles object with sticky positioning, z-index, background, and shadow.
Style Properties Applied:
position: sticky: keeps the column fixed during horizontal scrolltop:0for header cells, so they stick when the table scrolls verticallyleftorright: position based on the pinning sidezIndex: 20 for headers, 10 for body cellsbackgroundColor:var(--background), so the cell is opaqueboxShadow: a divider usingvar(--border)on pinned column edges
Scroll Handler Factory
Section titled “Scroll Handler Factory”The scroll listener shared by every body component (DataTableBody, DataTableVirtualizedBody, DataTableVirtualizedDndBody, DataTableVirtualizedDndColumnBody). One copy means a scroll fix reaches all four bodies, and custom bodies can reuse it.
createScrollHandler
Section titled “createScrollHandler”Builds a scroll handler that reads container metrics on each scroll event and calls:
onScrollwith aScrollEventsnapshot (scrollTop,scrollHeight,clientHeight,isTop,isBottom,percentage)onScrolledTopwhenscrollTop === 0onScrolledBottomwhen withinscrollThresholdpixels of the end
Attach the returned listener with addEventListener("scroll", handler, { passive: true }). The browser can then keep scrolling on its compositor thread (smoother on mobile and with virtual scroll).
import { createScrollHandler } from "@/components/niko-table/lib/create-scroll-handler"
React.useEffect(() => { const container = containerRef.current if (!container) return if (!onScroll && !onScrolledTop && !onScrolledBottom) return
const handleScroll = createScrollHandler({ onScroll, onScrolledTop, onScrolledBottom, scrollThreshold: 50, }) container.addEventListener("scroll", handleScroll, { passive: true }) return () => container.removeEventListener("scroll", handleScroll)}, [onScroll, onScrolledTop, onScrolledBottom])Parameters
Section titled “Parameters”Single options object:
| Name | Type | Default | Description |
|---|---|---|---|
onScroll |
(event: ScrollEvent) => void (optional) |
- | Called on every scroll event with a snapshot of container metrics |
onScrolledTop |
() => void (optional) |
- | Called when scrollTop === 0 |
onScrolledBottom |
() => void (optional) |
- | Called when within scrollThreshold of the bottom |
scrollThreshold |
number |
50 |
Pixel distance from the bottom that triggers onScrolledBottom (use a higher value for earlier prefetching) |
Returns
Section titled “Returns”(event: Event) => void: the listener to attach. Your callbacks are passed once when you build it, so build it in a useEffect keyed on the same callbacks.
- For virtualized infinite scroll, use
DataTableVirtualizedBody’sonNearEndandprefetchThresholdinstead ofonScrolledBottom.onNearEndfollows the virtualizer index, so it also catches:- fast scrolls and scrollbar drags
scrollToIndex()jumps- first renders where the data does not fill the viewport
- The handler reads
event.currentTarget. Attach it directly to the scroll container, not a parent.
Row Click Guard
Section titled “Row Click Guard”The row-click guard shared by every body component (DataTableBody, DataTableDndBody, DataTableDndColumnBody, DataTableVirtualizedBody, DataTableVirtualizedDndBody, DataTableVirtualizedDndColumnBody). The list of interactive elements (action buttons, checkboxes, links, radix collection items, etc.) lives in one place. To ignore a new data-slot, edit one file instead of six.
isInteractiveClickTarget
Section titled “isInteractiveClickTarget”Returns true when the click hit (or is inside) an interactive element, so onRowClick should not run. The per-row bodies (DataTableBody, DataTableVirtualizedBody) use it. They already know the row from event.currentTarget.dataset.rowId.
import { isInteractiveClickTarget } from "@/components/niko-table/lib/row-click"
const handleRowClick = (event: React.MouseEvent<HTMLElement>) => { if (isInteractiveClickTarget(event.target as HTMLElement)) return const rowId = event.currentTarget.dataset.rowId if (!rowId) return const row = table.getRow(rowId) if (!row) return onRowClick(row.original, event)}resolveRowFromClick
Section titled “resolveRowFromClick”For delegated <tbody> handlers (the DnD bodies use it). Returns the matched row, or null if the click should be ignored. That happens when the click hit an interactive child, or when no row could be found from the closest tr[data-row-id].
import { resolveRowFromClick } from "@/components/niko-table/lib/row-click"
const handleRowClick = (event: React.MouseEvent<HTMLElement>) => { const row = resolveRowFromClick(event.target as HTMLElement, table) if (!row) return onRowClick(row.original, event)}- The interactive-element list lives in
isInteractiveClickTarget. Add new ignored elements there. - Rows need
data-row-id={row.id}for delegated lookup. All built-in bodies set it. Custom bodies should too.
Additional Constants
Section titled “Additional Constants”SYSTEM_COLUMN_IDS
Section titled “SYSTEM_COLUMN_IDS”IDs of system columns (such as row selection and row expansion). Used for smart pinning and feature detection.
import { SYSTEM_COLUMN_IDS } from "@/components/niko-table/lib/constants"
// Available IDs:SYSTEM_COLUMN_IDS.SELECT // "select" - Row selection checkbox columnSYSTEM_COLUMN_IDS.EXPAND // "expand" - Row expansion toggle columnSYSTEM_COLUMN_IDS.ACTIONS // "actions" - Row actions (kebab menu) columnSYSTEM_COLUMN_ID_LIST
Section titled “SYSTEM_COLUMN_ID_LIST”The SYSTEM_COLUMN_IDS values as an array. Use it to check whether a column ID is a system column.
import { SYSTEM_COLUMN_ID_LIST } from "@/components/niko-table/lib/constants"
// ["select", "expand"]const isSystemColumn = SYSTEM_COLUMN_ID_LIST.includes(columnId)ERROR_MESSAGES
Section titled “ERROR_MESSAGES”Standard error messages used across the library.
import { ERROR_MESSAGES } from "@/components/niko-table/lib/constants"
// Available messages:ERROR_MESSAGES.DEPRECATED_GLOBAL_JOIN_OPERATORFaceted Options Builder
Section titled “Faceted Options Builder”Faceted-filter components use it inside to turn raw column data into the { label, value, count } shape the filter UI needs. Most people never import it.
buildFacetedOptions
Section titled “buildFacetedOptions”Builds unique { label, value, count } entries for the faceted-filter dropdown from a TanStack Table column and rows. With dynamicCounts, counts update when other filters change. DataTableFacetedFilter and TableColumnFacetedFilter use it inside.
import { buildFacetedOptions } from "@/components/niko-table/lib/build-faceted-options"
const options = buildFacetedOptions( table, table.getCoreRowModel().rows, "category", // accessorKey table.state.columnFilters, table.state.globalFilter, { limitToFilteredRows: true, dynamicCounts: true, showCounts: true, autoOptionsFormat: "capitalize", },)// → [{ label: "Electronics", value: "electronics", count: 12 }, ...]- The faceted-filter wrappers use this module. For a custom faceted UI, use
useGeneratedOptions(inhooks/). It wraps this helper with React state. - It runs in O(n) over the column’s cell values. Calling it on each render is fine for typical column counts.
Row Filtering Helpers
Section titled “Row Filtering Helpers”Internal helpers that turn globalFilter and column filters into the final visible rows. DataTableRoot uses them on top of the filtered row model registered in lib/data-table-features.ts.
filter-rows.ts
Section titled “filter-rows.ts”The row-filtering logic behind the table’s filtered row model. It combines column filters with the global filter, picks the right extendedFilter / globalFilter / numberRangeFilter / dateRangeFilter from column meta, and returns the visible rows.
This module is internal to the filter pipeline. You normally reach it through the filterFns registered in tableFeatures() (see lib/data-table-features.ts). DataTableRoot passes them to the table for you. For a fully custom filter pipeline, import the named helpers from this file. See the source for the current exports.
Column Sizing Layout
Section titled “Column Sizing Layout”Helpers that make a resizable table fill its container and keep header labels readable. Flex fill and header-fit turn on automatically with column resizing. Auto-fit and persistence are opt-in.
resolveFlexColumnIds
Section titled “resolveFlexColumnIds”Picks which column(s) render widthless so they take the leftover row width (flex fill).
- On by default for resizable tables. The first non-pinned, resizable data column takes the extra space, so the table fills its container with no gap on the right.
- Pure layout: it never writes
columnSizing, so nothing gets saved.
Overrides via column or table meta:
meta.flex === true: that column flexes.meta.flex === false: that column is skipped.TableMeta.disableFlexFill === true: fill is off for the whole table.- A column the user resized keeps their width. The fill moves to the next eligible column.
import { resolveFlexColumnIds } from "@/components/niko-table/lib/flex-columns"
const flexIds = resolveFlexColumnIds(table)// → Set { "name" } — the default first data column fills the surplusParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
table |
DataTableInstance<TData> |
TanStack Table instance |
Returns
Section titled “Returns”ReadonlySet<string> - Column ids to render widthless. Empty when fill is off (disableFlexFill, resizing disabled) or no column is eligible.
resolveColumnWidth
Section titled “resolveColumnWidth”The width to render for one column. It keeps the flex and header-fit rules in one place, so the header, body cells, and min-width lock agree.
- Resizing off: the declared
size. - Flex column:
undefined. - User-resized column: exactly
getSize(). - Otherwise: at least the header’s natural width, so the label is never cut off on load.
- Pure layout:
headerMinWidthsis measured and never written tocolumnSizing.
import { resolveColumnWidth } from "@/components/niko-table/lib/flex-columns"
const width = resolveColumnWidth(column, { resizing: true, isFlex: flexIds.has(column.id), columnSizing: table.state.columnSizing, headerMinWidths,})Parameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
column |
DataTableColumn<TData> |
TanStack Table column instance |
params.resizing |
boolean |
Whether column resizing is enabled |
params.isFlex |
boolean |
Whether this column is a flex (fill) column |
params.columnSizing |
ColumnSizingState |
Current column sizing state |
params.headerMinWidths |
ReadonlyMap<string, number> |
Measured header widths (from useHeaderMinWidths) |
Returns
Section titled “Returns”number | string | undefined - The width to render (undefined for the flex column or an unsized off state).
useHeaderMinWidths
Section titled “useHeaderMinWidths”Measures each header’s natural width off-DOM (a reusable canvas, so no reflow). Columns the user has not resized get at least that width (header-fit), so labels are not cut off on load.
- Returns: a
columnId → minWidthmap. - Resized columns: left alone.
- Pure measurement: nothing is written to
columnSizing. - Recomputes: only when visible columns, their labels, or the header font change.
import { useHeaderMinWidths } from "@/components/niko-table/lib/use-header-min-widths"
const headerMinWidths = useHeaderMinWidths(table, scrollElement, resizingEnabled)Parameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
table |
DataTableInstance<TData> |
TanStack Table instance |
scrollElement |
HTMLElement | null |
The table’s scroll container (for reading fonts) |
enabled |
boolean |
Whether header-fit measurement is active |
Returns
Section titled “Returns”ReadonlyMap<string, number> - Minimum width in px per column id (label width + header chrome).
useColumnAutoFit
Section titled “useColumnAutoFit”An even-split alternative to single-column flex fill.
- What it does: on load (and when the container grows or columns toggle), it gives each resizable column an equal share of the leftover space. It seeds
columnSizing. - When it stops: for good once the user resizes a column or a saved
columnSizingis restored. - How to use it: most people add the opt-in
<DataTableColumnAutoFit />component instead of calling this hook.
import { useColumnAutoFit } from "@/components/niko-table/lib/use-column-auto-fit"
useColumnAutoFit(table, scrollElement, resizingEnabled)Parameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
table |
DataTableInstance<TData> |
TanStack Table instance |
scrollElement |
HTMLElement | null |
The table’s scroll container (measured for width) |
enabled |
boolean |
Whether auto-fit is active (needs resizing on) |
Returns
Section titled “Returns”void - Seeds columnSizing via table.setColumnSizing.
useColumnSizingPersistence
Section titled “useColumnSizingPersistence”Opt-in localStorage saving for resized column widths. Column sizing is controlled state on <DataTableRoot>, so this hook owns it. Pass the returned columnSizing and onColumnSizingChange to the table, and widths survive reloads.
- Writes at once: resizing runs in
onEndmode, so it saves once per drag. - Syncs across tabs: via the native
storageevent. An unchanged read keeps the same state object, so idle tabs do not re-render. - Cleans bad data: corrupt or hand-edited storage never reaches
column.getSize().
import { useColumnSizingPersistence } from "@/components/niko-table/lib/use-column-sizing-persistence"
const { columnSizing, onColumnSizingChange, resetColumnSizing } = useColumnSizingPersistence(`orders-table:${orgId}`)
<DataTableRoot data={rows} columns={columns} state={{ columnSizing }} onColumnSizingChange={onColumnSizingChange}> <DataTable> <DataTableHeader /> <DataTableBody /> </DataTable> <DataTableColumnResize /></DataTableRoot>Parameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
storageKey |
string |
localStorage key. Scope it per table (and per tenant/user). |
Returns
Section titled “Returns”ColumnSizingPersistence: an object with:
| Property | Type | Description |
|---|---|---|
columnSizing |
ColumnSizingState |
Controlled widths to pass to <DataTableRoot state={{ … }} /> |
onColumnSizingChange |
OnChangeFn<ColumnSizingState> |
Pass to <DataTableRoot onColumnSizingChange={…} /> |
resetColumnSizing |
() => void |
Clears stored widths and resets every column to its declared size |