Data Table
This is an in-depth guide on how to use the NvDatatable component, covering column configuration, custom cell rendering, pagination modes, and best practices. For API documentation and interactive examples, see the component documentation.
Key Features
- Custom Cell Renderers: Full control over cell content with custom render functions for complex visualizations and interactions
- Custom Header Renderers: Customize column headers with tooltips, icons, or custom styling
- Full TypeScript Support: Comprehensive type definitions with generic row typing for complete type safety
- Three Pagination Modes: Client-side, server-side, and infinite scroll pagination support
- Global Filtering: Client-side and server-side filtering with custom filter UI via render props
- Row Selection: Single and multiple row selection with checkboxes, persistent across pagination
- Expandable Rows: Render arbitrary content beneath rows, with optional expand/collapse toggle
- Extensive Column Configuration: Control width, resizing, hiding, and custom headers with flexible configuration options
- Built on TanStack Table: Leverages the industry-standard TanStack Table library for robust, performant data management
Basic Usage
The simplest implementation requires only column definitions and row data:
import { NvDatatable, makeColumn } from '@nova-design-system/nova-react';
interface Employee {
id: number;
name: string;
email: string;
department: string;
salary: number;
}
// Create column factory
const col = makeColumn<Employee>();
const columns = [
col({ field: 'name', headerName: 'Full Name' }),
col({ field: 'email', headerName: 'Email Address' }),
col({ field: 'department', headerName: 'Department' }),
col({ field: 'salary', headerName: 'Salary' }),
];
const employees: Employee[] = [
{
id: 1,
name: 'John Smith',
email: 'john.smith@company.com',
department: 'Engineering',
salary: 75000,
},
// ... more data
];
function MyTable() {
return (
<NvDatatable
columns={columns}
rows={employees}
/>
);
}
Advanced Column Configuration
Columns support extensive configuration options for precise control. View the full column configuration reference for details.
interface Product {
id: number;
name: string;
price: number;
status: 'active' | 'inactive';
}
const col = makeColumn<Product>();
const advancedColumns = [
col({
field: 'name',
headerName: 'Product Name',
width: 200,
resizable: true,
renderCell: ({ value }) => (
<div className="font-semibold">
{value}
</div>
),
}),
col({
field: 'price',
headerName: 'Price',
width: 120,
// Format number to currency string
valueFormatter: ({ value }) => `$${value.toFixed(2)}`,
renderCell: ({ value }) => (
<span className="font-mono text-feedback-success-low">
{value}
</span>
),
}),
col({
field: 'status',
headerName: 'Status',
// No width specified - this column will take remaining space
renderCell: ({ value }) => (
<NvBadge
label={value}
color={value === 'active' ? 'success' : 'error'}
/>
),
}),
];
TypeScript
The NvDatatable component provides full TypeScript support with automatic type inference using the makeColumn factory function. This ensures type safety throughout your column definitions, especially when using valueFormatter and renderCell.
Using makeColumn Factory
The recommended approach is to use the makeColumn factory function:
import { NvDatatable, makeColumn } from '@nova-design-system/nova-react';
// Define your data interface
interface Employee {
id: number;
name: string;
email: string;
salary: number;
isActive: boolean;
}
// Create a column factory for your data type
const col = makeColumn<Employee>();
// Define columns with full type safety
const columns = [
col({ field: 'id', headerName: 'ID' }),
col({ field: 'name', headerName: 'Name' }),
col({ field: 'email', headerName: 'Email' }),
col({ field: 'salary', headerName: 'Salary' }),
];
// Use with your data
const employees: Employee[] = [
{ id: 1, name: 'John Doe', email: 'john@example.com', salary: 75000, isActive: true },
{ id: 2, name: 'Jane Smith', email: 'jane@example.com', salary: 85000, isActive: true },
];
function MyTable() {
return <NvDatatable columns={columns} rows={employees} />;
}
Type Flow with valueFormatter
The makeColumn factory ensures that when you use valueFormatter, the return type automatically flows to renderCell:
interface Employee {
id: number;
name: string;
salary: number; // number type
}
const col = makeColumn<Employee>();
const columns = [
col({
field: 'salary',
headerName: 'Salary',
// valueFormatter receives number, returns string
valueFormatter: ({ value }) => `$${value.toLocaleString()}`,
// renderCell receives the formatted string (not the original number)
renderCell: ({ value }) => (
<span className="font-mono">{value}</span>
// 'value' is typed as string ✓
),
}),
];
Complex Data Types
The factory function works seamlessly with complex data types like objects and arrays:
interface User {
id: number;
name: { first: string; last: string };
skills: string[];
}
const col = makeColumn<User>();
const columns = [
col({
field: 'name',
headerName: 'Full Name',
// Transform nested object to string
valueFormatter: ({ value }) => `${value.first} ${value.last}`,
}),
col({
field: 'skills',
headerName: 'Skills',
// Transform array to string
valueFormatter: ({ value }) => value.join(', '),
}),
];
Automatic Column Generation
When you don't provide column definitions, NvDatatable inspects the row data and builds the columns for you. This is handy for quickly displaying data without wiring up a column for every field.
// Omit `columns` — the datatable infers them from the row data.
const rows = [
{ id: 1, firstName: 'Ada Lovelace', salary: 95000, isActive: true, startDate: '2021-03-15' },
{ id: 2, firstName: 'Alan Turing', salary: 88000, isActive: false, startDate: '2022-07-01' },
];
<NvDatatable rows={rows} sorting={{}} />;
The generated columns follow these rules:
- One column per key found in the data (the union of keys across the first rows, in first-seen order).
- Headers are humanized from field names —
firstNamebecomes "First Name",created_atbecomes "Created At". - Cells are rendered based on the inferred value type:
- Boolean → centered
True/Falsetext - Number → right-aligned
- Date (a
Datevalue or ISO date string) → locale-formatted - Array of objects → expandable row detail with a nested auto-generated datatable
- Array of primitives → comma-joined list
- Plain object → compact JSON
- String → rendered as-is
- Boolean → centered
- Sorting and filtering keep operating on the raw underlying values, not the formatted display text.
- Explicit columns always take precedence — pass
columnsto override any or all of the generated columns.
Tip: You can control cell alignment on any column (generated or explicit) with the
alignproperty:'left' | 'center' | 'right'.
Master-detail from nested object collections
When a field's values are arrays of objects, auto-generation does not render them as a column — it promotes them to an expandable row detail containing a nested, auto-generated datatable:
- Each such field becomes its own labelled section (humanized field name) with its own nested datatable, which auto-generates its columns the same way (recursively).
- A model with several nested-object fields produces several stacked detail sections under a single expand toggle on the row.
- If a given row's list is empty, that section is omitted for that row.
- Arrays of primitives are not details — they stay a column rendered as a comma-joined list.
const rows = [
{
id: 1,
name: 'Acme',
orders: [{ orderId: 'A-1', amount: 250 }],
invoices: [{ invoiceId: 'INV-1', total: 250, paid: true }],
},
];
// `orders` and `invoices` become two stacked detail tables; `id`/`name` stay columns.
<NvDatatable rows={rows} />;
Master-detail relies on the datatable's expandable system, currently available in React and Blazor.
Columns
Each column definition supports the following properties:
| Property | Required | Type | Description |
|---|---|---|---|
field | ✅ | keyof Row | The key from your data object to display |
headerName | - | string | Custom header text (defaults to field name) |
width | - | number | Column width in pixels |
align | - | 'left' | 'center' | 'right' | Horizontal alignment of the column's cell content. Explicit columns default to left; auto-generated columns default to center (numbers right-aligned) |
resizable | - | boolean | Whether users can resize the column (default: true) |
hidden | - | boolean | Hide the column from display |
valueFormatter | - | function | Transform the raw value before rendering (returns string or number) |
renderCell | - | function | Custom cell rendering function |
renderHeader | - | function | Custom header rendering function |
Value Formatters
The valueFormatter function transforms raw cell values before rendering, providing a clean way to handle common data transformations without requiring full JSX rendering.
When to Use valueFormatter vs renderCell
- Use
valueFormatterwhen you need to transform data to a different format (dates, arrays, nested objects) but don't need custom JSX styling - Use
renderCellwhen you need custom presentation with styled components, badges, buttons, or complex layouts - Use both together to first transform the data with
valueFormatter, then style it withrenderCell
Function Signature
valueFormatter?: (params: NvTableValueFormatterParams<Row, Row[K], K>) => F
Function Parameters:
The function receives a single params object with the following properties:
| Parameter | Type | Description |
|---|---|---|
value | Row[K] | The raw cell value from the data |
row | Row | The complete row object (useful for accessing other fields) |
field | K | The field name being formatted |
Returns: Any type F that will be passed to renderCell. The return type is inferred from your function and automatically typed in renderCell.
Common Use Cases
Format Dates:
col({
field: 'birthDate',
headerName: 'Birth Date',
valueFormatter: ({ value }) => {
if (typeof value === 'string') {
return new Date(value).toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
});
}
return '';
},
})
Join Arrays:
col({
field: 'skills',
headerName: 'Skills',
valueFormatter: ({ value }) => {
if (Array.isArray(value)) {
return value.join(', ');
}
return '';
},
})
Access Nested Objects:
col({
field: 'person',
headerName: 'Full Name',
valueFormatter: ({ value }) => {
if (typeof value === 'object' && value !== null) {
const person = value as { first: string; last: string };
return `${person.first} ${person.last}`;
}
return '';
},
})
Combining valueFormatter with renderCell
You can use both together - the valueFormatter runs first to transform the data, then renderCell handles the presentation:
col({
field: 'isActive',
headerName: 'Status',
// First, format the boolean to a string
valueFormatter: ({ value }) => (value ? 'Active' : 'Inactive'),
// Then, style it with a badge
renderCell: ({ value }) => (
<NvBadge
label={String(value)}
color={value === 'Active' ? 'success' : 'neutral'}
/>
),
})
Custom Cell Renderers
The renderCell function allows you to render any React component using the row's data:
Function Parameters: NvTableRenderCellParams<T, T[keyof T]>
| Parameter | Type | Description |
|---|---|---|
value | Row[K] | The cell's actual value (after valueFormatter if provided) |
row | Row | Complete row object for accessing other fields |
field | K | The field name being rendered |
rowIndex | number | Zero-based row index |
Examples:
Formatting Numbers and Currency:
col({
field: 'price',
renderCell: ({ value }) => (
<span className="font-mono">
${typeof value === 'number' ? value.toLocaleString() : '0'}
</span>
),
})
Status Badges:
col({
field: 'status',
renderCell: ({ value }) => (
<NvBadge
label={value}
color={getStatusColor(value)}
/>
),
})
Custom Header Renderers
The renderHeader function allows you to customize column headers with custom React components, such as tooltips, icons, or styled text.
Function Parameters: NvTableRenderHeaderParams<K>
| Parameter | Type | Description |
|---|---|---|
headerName | string | The display name for the column header (from headerName prop or field name) |
field | K | The field name being rendered |
Examples:
Header with Tooltip:
col({
field: 'name',
headerName: 'Full Name',
renderHeader: ({ headerName }) => (
<NvTooltip message="The employee's complete legal name" placement="top">
<span>{headerName}</span>
</NvTooltip>
),
})
Header with Icon:
col({
field: 'salary',
headerName: 'Salary',
renderHeader: ({ headerName }) => (
<span className="flex items-center gap-1">
{headerName}
<NvIcon name="cash-banknote" size="sm" />
</span>
),
})
Header with Custom Styling:
col({
field: 'priority',
headerName: 'Priority',
renderHeader: ({ headerName }) => (
<span className="text-feedback-error-low font-bold">
{headerName} *
</span>
),
})
Column Width Best Practices
When configuring column widths, follow these guidelines for optimal behavior:
⚠️ Important: Do not set width on ALL columns. Always leave at least one column without a specified width to take up the remaining space. Setting widths on every column can cause column resizing to behave incorrectly due to browser table rendering constraints.
Good Practice:
const columns = [
col({ field: 'id', width: 80 }), // Fixed narrow column
col({ field: 'name', width: 200 }), // Fixed wider column
col({ field: 'email' }), // No width - takes remaining space
col({ field: 'actions', width: 150 }), // Fixed action column
];
Avoid:
const columns = [
col({ field: 'id', width: 80 }), // ❌ All columns have width
col({ field: 'name', width: 200 }), // ❌ Can cause resizing issues
col({ field: 'email', width: 300 }), // ❌ Browser table constraints
col({ field: 'actions', width: 150 }), // ❌ No flexible column
];
Tips:
- Set fixed widths for columns with predictable content (IDs, actions, status badges)
- Leave content columns (names, descriptions) without fixed widths for flexibility
- Use horizontal scrolling for tables with many columns rather than cramming them into viewport
- Note: Even with fixed widths, columns may still expand if:
- Users manually resize columns (when resizable is enabled)
- Content is too wide to fit and cannot be wrapped or collapsed (browser will auto-expand to prevent overflow)
Pagination
NvDatatable supports three pagination modes to handle different data loading scenarios:
Pagination Modes
- Client-Side Pagination: All data is loaded at once, pagination handled in the browser
- Server-Side Pagination: Data fetched page-by-page from server with button navigation
- Infinite Scroll: Data loads continuously as user scrolls, accumulating all loaded rows
Client-Side Pagination
Best for datasets under a few thousand rows where all data can be loaded at once.
Enable pagination: pass the pagination prop. Default UI: omit renderPagination to use the built-in nv-paginationtable component.
import { NvDatatable, makeColumn } from '@nova-design-system/nova-react';
interface Employee {
id: number;
name: string;
email: string;
department: string;
}
function MyTable() {
const col = makeColumn<Employee>();
const columns = [
col({ field: 'id', headerName: 'ID' }),
col({ field: 'name', headerName: 'Name' }),
col({ field: 'email', headerName: 'Email' }),
col({ field: 'department', headerName: 'Department' }),
];
const allData: Employee[] = [
{ id: 1, name: 'John Doe', email: 'john@example.com', department: 'Engineering' },
{ id: 2, name: 'Jane Smith', email: 'jane@example.com', department: 'Marketing' },
// ... more data (100+ rows)
];
return (
// Enable pagination + use default nv-paginationtable (no renderPagination)
<NvDatatable
columns={columns}
rows={allData}
pagination={{
initialPageSize: 20,
pageSizeOptions: [10, 20, 50, 100],
}}
/>
);
}
Custom pagination UI: pass renderPagination to render your own controls:
<NvDatatable
columns={columns}
rows={allData}
pagination={{
initialPageSize: 20,
pageSizeOptions: [10, 20, 50, 100],
}}
renderPagination={(api) => (
<div>
<button onClick={api.previousPage} disabled={!api.canPreviousPage}>
Previous
</button>
<span>Page {api.pageIndex + 1} of {api.pageCount}</span>
<button onClick={api.nextPage} disabled={!api.canNextPage}>
Next
</button>
<select
value={api.pageSize}
onChange={(e) => api.setPageSize(Number(e.target.value))}
>
{[10, 20, 50].map(size => (
<option key={size} value={size}>{size} rows</option>
))}
</select>
</div>
)}
/>
Key Points:
- Enable pagination: pass the
paginationprop (e.g.initialPageSize,pageSizeOptions). - Default UI: do not pass
renderPagination→nv-paginationtableis used automatically (client mode only). - Custom UI: pass
renderPaginationto render your own controls. - Hide UI but keep logic: pass
renderPagination={() => null}(e.g. for infinite scroll). - Pass all data to the
rowsprop; no server requests needed for page changes.
Server-Side Pagination
Best for large datasets where you want to fetch data page-by-page.
⚠️ Important: In server-side mode, you must provide your own pagination UI via the renderPagination prop. Unlike client-side mode, the default nv-paginationtable component is not automatically rendered in server mode. This is because server-side pagination requires custom logic to fetch data from your API when users navigate between pages.
function MyTable() {
const [currentPage, setCurrentPage] = useState(0);
const [pageSize, setPageSize] = useState(10);
// Fetch only current page data
const { data, totalCount } = useFetchData(currentPage, pageSize);
const handlePaginationChange = ({ pageIndex, pageSize }) => {
setCurrentPage(pageIndex);
setPageSize(pageSize);
// Fetch new page data here
};
return (
<NvDatatable
columns={columns}
rows={data} // Only current page data
pagination={{
mode: 'server',
totalRowCount: totalCount,
initialPageSize: 10,
onPaginationChange: handlePaginationChange,
}}
renderPagination={(api) => (
<div>
<button onClick={api.firstPage} disabled={!api.canPreviousPage}>
First
</button>
<button onClick={api.previousPage} disabled={!api.canPreviousPage}>
Previous
</button>
<span>Page {api.pageIndex + 1} of {api.pageCount}</span>
<button onClick={api.nextPage} disabled={!api.canNextPage}>
Next
</button>
<button onClick={api.lastPage} disabled={!api.canNextPage}>
Last
</button>
</div>
)}
/>
);
}
Key Points:
- ⚠️ Required: You must provide
renderPaginationto display pagination controls (no default UI in server mode) - Pass only current page data to
rowsprop (data is replaced on page change) - Provide
totalRowCountortotalPageCount - Use
onPaginationChangecallback to fetch new data - Parent component manages which page to display
Infinite Scroll
Best for continuously loading data as user scrolls, like social media feeds.
function MyTable() {
const [loadedData, setLoadedData] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const [hasMore, setHasMore] = useState(true);
const loadMore = async () => {
setIsLoading(true);
const newData = await fetchNextPage();
setLoadedData(prev => [...prev, ...newData]); // Append new data
setHasMore(newData.length > 0);
setIsLoading(false);
};
return (
<div style={{ maxHeight: '600px', overflow: 'auto' }}>
<NvDatatable
columns={columns}
rows={loadedData} // Accumulated data
pagination={{
mode: 'infinite',
hasMore,
isLoading,
loadMoreThreshold: 500, // px from bottom to trigger load
onLoadMore: loadMore,
totalRowCount: 1000, // Optional
}}
renderPagination={(api) => (
api.isLoading ? (
<div>Loading more...</div>
) : api.hasMore ? (
<div>Scroll to load more</div>
) : (
<div>All data loaded</div>
)
)}
/>
</div>
);
}
Key Points:
- Pass accumulated data to
rowsprop (data is appended on load) - Wrap table in scrollable container or let it grow naturally
- Uses IntersectionObserver to detect when last row is near viewport
- Parent component maintains accumulated data array
- Set
hasMore: falsewhen all data is loaded
Pagination Configuration
| Property | Required | Type | Default | Description |
|---|---|---|---|---|
mode | ✅ | 'client' | 'server' | 'infinite' | - | Pagination mode |
initialPageSize | - | number | 10 | Initial page size |
pageSizeOptions | - | number[] | [10, 25, 50, 100] | Available page size options |
| Server-side specific | ||||
totalRowCount | - | number | - | Total number of rows (for server-side pagination) |
totalPageCount | - | number | - | Total number of pages (for server-side pagination) |
onPaginationChange | - | function | - | Callback when pagination state changes |
| Infinite scroll specific | ||||
hasMore | - | boolean | - | Whether there are more items to load |
isLoading | - | boolean | - | Whether data is currently loading |
loadMoreThreshold | - | number | 500 | Distance from bottom in pixels to trigger load |
onLoadMore | - | function | - | Callback to load more data |
Pagination API
Default Pagination Behavior:
- Client mode: When
renderPaginationis not provided, the datatable automatically renders thenv-paginationtablecomponent with full pagination controls. - Server mode: When
renderPaginationis not provided, no pagination UI is displayed. You must providerenderPaginationto create your own pagination controls.
Custom Pagination:
The renderPagination prop receives an API object with these properties and methods:
| Property | Type | Description |
|---|---|---|
| Current state | ||
pageIndex | number | Current page (zero-based) |
pageSize | number | Rows per page |
pageCount | number | Total number of pages |
rowCount | number | Total number of rows |
| Navigation methods | ||
firstPage | () => void | Navigate to first page |
previousPage | () => void | Navigate to previous page |
nextPage | () => void | Navigate to next page |
lastPage | () => void | Navigate to last page |
setPageIndex | (index: number) => void | Navigate to specific page by index |
setPageSize | (size: number) => void | Change page size |
| State queries | ||
canPreviousPage | boolean | Whether previous page is available |
canNextPage | boolean | Whether next page is available |
| Infinite scroll only | ||
isLoading | boolean | Currently loading data |
hasMore | boolean | More data available |
Expandable Rows
NvDatatable supports rendering arbitrary content beneath rows via the expandable prop. Two modes are available: always-visible (content is persistently shown) and collapsible (content is hidden behind an expand/collapse toggle).
Configuration
| Property | Type | Description |
|---|---|---|
renderExpandedContent | (params: { row: T; rowIndex: number }) => ReactNode | null | Required. Return the content to render beneath a row, or null for no content. |
collapsible | boolean | When true, shows an expand/collapse toggle and hides content by default. (default: false) |
expandedState | ExpandedState | Controlled expanded state (collapsible only). true for all expanded, or Record<string, boolean>. |
onExpandedChange | (state: ExpandedState) => void | Callback when expanded state changes (collapsible only). |
getRowCanExpand | (row: T) => boolean | Control which rows can be expanded (collapsible only). |
toggleColumnWidth | number | Width of the expand toggle column in pixels (default: 48). |
Always-Visible Content
When collapsible is false (default), expanded content renders persistently beneath each row that returns non-null content:
<NvDatatable
columns={columns}
rows={rows}
expandable={{
renderExpandedContent: ({ row }) => (
<p>Details for {row.name}: {row.email}</p>
),
}}
/>
Rows where renderExpandedContent returns null render normally without expanded content.
Collapsible Content
Set collapsible: true to add an expand/collapse toggle column. Rows are collapsed by default:
<NvDatatable
columns={columns}
rows={rows}
expandable={{
collapsible: true,
renderExpandedContent: ({ row }) => (
<p>Details for {row.name}: {row.email}</p>
),
}}
/>
Controlled Expanded State
Use expandedState and onExpandedChange for controlled expand/collapse behavior:
import { type ExpandedState } from '@nova-design-system/nova-react';
const [expanded, setExpanded] = useState<ExpandedState>({});
<NvDatatable
columns={columns}
rows={rows}
expandable={{
collapsible: true,
expandedState: expanded,
onExpandedChange: setExpanded,
renderExpandedContent: ({ row }) => (
<p>Details for {row.name}</p>
),
}}
/>
Set expandedState to true to expand all rows, or use a Record<string, boolean> to control individual rows.
Combining with Selection
Expandable rows work alongside row selection. When both selection and expandable.collapsible are enabled, the checkbox and the expand toggle share a single combined prefix column, with the two controls laid out side-by-side. The column width is the sum of selection.checkboxColumnWidth and expandable.toggleColumnWidth (both default to 48px, so the combined column defaults to 96px):
<NvDatatable
columns={columns}
rows={rows}
selection={{
mode: 'multiple',
getRowId: (row) => row.id.toString(),
selectedRowIds: selectedIds,
onSelectionChange: setSelectedIds,
}}
expandable={{
collapsible: true,
renderExpandedContent: ({ row }) => (
<p>Details for {row.name}</p>
),
}}
/>
Accessibility
- The expand/collapse toggle uses
aria-expandedandaria-controlslinking to the expanded content region. - The expanded content row has
role="region"with an accessible label. - The toggle is keyboard-operable via
EnterandSpacekeys. - The toggle meets the 44x44px minimum touch target size.
Interaction Behavior
- Clicking the expand toggle does not trigger
onRowClickor selection changes. - Expanded content is independent of sorting, filtering, and pagination state.
- When a row is filtered out, its expanded content is naturally hidden.
Sorting
NvDatatable provides comprehensive sorting capabilities with support for both client-side and server-side sorting, multi-column sorting, custom sort functions, and fine-grained control over sort behavior.
Sorting Modes
- Client-Side Sorting: All data is sorted in the browser automatically
- Server-Side Sorting: Sorting is handled by your API, table displays sorted results
Client-Side Sorting
Best for datasets that are fully loaded in the browser. The table automatically handles all sorting logic.
<NvDatatable
columns={columns}
rows={allData}
sorting={{
mode: 'client',
enableMultiSort: false, // Single column sorting (default)
enableSortingRemoval: true, // Allow cycling through none state
sortDescFirst: false, // Start with ascending (default)
}}
/>
Key Points:
- All data must be loaded in the
rowsprop - Sorting happens instantly in the browser
- No server requests needed
- Works seamlessly with client-side pagination
Basic Example
interface Product {
id: number;
name: string;
price: number;
stock: number;
}
const col = makeColumn<Product>();
const columns = [
col({ field: 'id', headerName: 'ID', width: 80 }),
col({ field: 'name', headerName: 'Product Name' }),
col({ field: 'price', headerName: 'Price', width: 120 }),
col({ field: 'stock', headerName: 'In Stock', width: 100 }),
];
function ProductTable() {
return (
<NvDatatable
columns={columns}
rows={products}
sorting={{ mode: 'client' }}
/>
);
}
Initial Sort State (Uncontrolled)
When you want the table to start sorted by a specific column but still let users change the sort by clicking headers, use initialSortState. It seeds the internal sort state on first render only — unlike sortState, it does not make the component controlled.
<NvDatatable
columns={columns}
rows={products}
sorting={{
initialSortState: [{ id: 'price', desc: true }],
}}
/>
When to use which:
initialSortState: your API returns unsorted data and you want a sensible default sort, but users should still be able to re-sort freely.sortState+onSortingChange: you need full control over sorting (e.g. server-side sorting, URL sync). PassingsortStatemakes the component controlled, so header clicks only take effect if you updatesortStateyourself in the callback.
If both sortState and initialSortState are provided, sortState wins.
Server-Side Sorting
Best for large datasets where sorting is performed by your backend API.
import {
NvDatatable,
type NvDataTableSortingState
} from '@nova-design-system/nova-react';
function MyTable() {
const [sortState, setSortState] = useState<NvDataTableSortingState>([]);
const handleSortingChange = (newSortState: NvDataTableSortingState) => {
setSortState(newSortState);
// Fetch sorted data from API and update data state
fetchData({
sortBy: newSortState[0]?.id,
sortOrder: newSortState[0]?.desc ? 'desc' : 'asc',
});
};
return (
<NvDatatable
columns={columns}
rows={data} // Pre-sorted data from API
sorting={{
mode: 'server',
sortState: sortState, // Controlled state
onSortingChange: handleSortingChange,
enableSortingRemoval: true,
}}
/>
);
}
Key Points:
- Pass pre-sorted data to
rowsprop - Use
sortStateto control which columns are sorted - Implement
onSortingChangecallback to fetch new data - Parent component manages sort state and data fetching
SortingState Format:
type SortingState = Array<{
id: string; // Column field name
desc: boolean; // true for descending, false for ascending
}>;
// Example: sorting by price descending
const sortState = [{ id: 'price', desc: true }];
// Example: multi-sort by department asc, then salary desc
const sortState = [
{ id: 'department', desc: false },
{ id: 'salary', desc: true },
];
Column-Level Sorting Options
Each column can have individual sorting configuration:
const columns = [
col({
field: 'id',
sortable: false, // Disable sorting for this column
}),
col({
field: 'name',
sortDescFirst: true, // Start with descending when clicked
}),
col({
field: 'rank',
invertSorting: true, // Lower numbers are better (rank 1 > rank 10)
}),
col({
field: 'score',
sortUndefined: 'last', // Put null/undefined values at the end
}),
col({
field: 'customData',
sortingFn: 'alphanumeric', // Use built-in sorting function
// Or provide custom function:
// sortingFn: (rowA, rowB, columnId) => {
// return rowA.original.customData.localeCompare(rowB.original.customData);
// }
}),
];
Multi-Column Sorting
Enable users to sort by multiple columns simultaneously while clicking column headers:
<NvDatatable
columns={columns}
rows={data}
sorting={{
mode: 'client',
enableMultiSort: true,
maxMultiSortColCount: 3, // Limit to 3 columns (optional)
}}
/>
Usage:
- Click a header to sort by that column
- Shift+Click another header to add secondary sort
- Continue Shift+Clicking to add more sort columns
- Click without Shift to reset to single-column sort
Custom Sorting Functions
For complex sorting logic, provide a custom sortingFn:
col({
field: 'status',
headerName: 'Status',
sortingFn: (rowA, rowB, columnId) => {
const statusOrder = { active: 1, pending: 2, inactive: 3 };
const a = statusOrder[rowA.original.status];
const b = statusOrder[rowB.original.status];
return a - b;
},
})
Built-in Sorting Functions:
You can also reference TanStack Table's built-in sorting functions by name:
'alphanumeric'- Natural alphanumeric sorting'alphanumericCaseSensitive'- Case-sensitive alphanumeric'text'- Case-insensitive text sorting'textCaseSensitive'- Case-sensitive text sorting'datetime'- Date and time sorting'basic'- Simple comparison (default)
col({
field: 'code',
sortingFn: 'alphanumeric', // Handles "A1", "A2", "A10" correctly
})
Sorting with Value Formatters
⚠️ Important: When using valueFormatter with sorting, be aware that sorting operates on the formatted value, not the original data. This can cause unexpected sorting behavior, especially with dates and numbers.
The Problem
When you format a value for display, the sorting function sees the formatted string instead of the original data:
col({
field: 'employedAt',
headerName: 'Employed At',
sortingFn: 'datetime',
// ❌ WRONG: This formats the date for sorting
valueFormatter: ({ value }) => new Date(value).toLocaleDateString(),
})
Result: Dates sort alphabetically by their formatted strings:
- 9/1/2024
- 8/1/2027
- 12/1/2027
Instead of chronologically as intended.
The Solution: Use renderCell
Keep the original value intact for sorting by using renderCell instead of valueFormatter:
col({
field: 'employedAt',
headerName: 'Employed At',
sortingFn: 'datetime',
// ✅ CORRECT: Format only for display, sorting uses original value
renderCell: ({ value }) => new Date(value).toLocaleDateString(),
})
Result: Dates sort correctly:
- 8/1/2027
- 12/1/2027
- 9/1/2024 (actually from 2024, not 2027)
When You Can Use Both Sorting and valueFormatter
You can safely use valueFormatter with sorting when displaying the data in a different format doesn't interfere with the underlying sort logic. This is particularly useful with nested objects where you want to transform the display format while sorting operates on the original structure.
Example: Displaying names in "Last, First" format while sorting by last name:
interface Employee {
id: number;
name: { first: string; last: string };
department: string;
}
const col = makeColumn<Employee>();
const columns = [
col({
field: 'name',
headerName: 'Employee Name',
// Transform nested object to display "lastName, firstName"
valueFormatter: ({ value }) => `${value.last}, ${value.first}`,
// Sorting still works correctly on the original object
// The table will sort by last name automatically
}),
];
// Data displays as: "Smith, John" but sorts correctly by last name
const employees: Employee[] = [
{ id: 1, name: { first: 'John', last: 'Smith' }, department: 'Engineering' },
{ id: 2, name: { first: 'Jane', last: 'Anderson' }, department: 'HR' },
{ id: 3, name: { first: 'Bob', last: 'Wilson' }, department: 'Sales' },
];
This works because the sorting operates on the original nested object structure, while valueFormatter only affects the display. The table can still access name.last for sorting purposes.
Alternative: Custom Sorting Function
If you need both value transformation and custom sort logic, use a custom sortingFn:
col({
field: 'employedAt',
headerName: 'Employed At',
// Custom sort using original values
sortingFn: (rowA, rowB) => {
const dateA = new Date(rowA.original.employedAt).getTime();
const dateB = new Date(rowB.original.employedAt).getTime();
return dateA - dateB;
},
// Format for display
valueFormatter: ({ value }) => new Date(value).toLocaleDateString(),
})
Key Takeaway: Use renderCell for formatting display values when you need accurate sorting of the underlying data. Reserve valueFormatter for transformations that don't affect sort accuracy, or combine it with a custom sortingFn.
Handling Undefined Values
Control where null and undefined values appear in sorted results:
col({
field: 'optionalField',
sortUndefined: 'last', // Options: 'first' | 'last' | false | -1 | 1
})
| Value | Behavior |
|---|---|
'first' or -1 | Undefined values appear first |
'last' or 1 | Undefined values appear last |
false | Undefined values maintain original order |
Inverted Sorting
For rankings or scenarios where lower numbers are better:
col({
field: 'rank',
headerName: 'Rank',
invertSorting: true, // Rank 1 will appear before rank 10 in "ascending" sort
})
Sorting Configuration Reference
Global Sorting Config (sorting prop):
| Property | Required | Type | Default | Description |
|---|---|---|---|---|
mode | ✅ | 'client' | 'server' | - | Sorting mode |
enableMultiSort | - | boolean | false | Enable multi-column sorting with Shift+Click |
enableSortingRemoval | - | boolean | true | Allow cycling through to "no sort" state |
maxMultiSortColCount | - | number | - | Maximum number of columns for multi-sort |
sortDescFirst | - | boolean | false | Start with descending sort as first toggle state |
initialSortState | - | SortingState | [] | Uncontrolled initial sort applied on first render; ignored when sortState is set |
| Server-side specific | ||||
sortState | - | SortingState | [] | Controlled sort state |
onSortingChange | - | (sorting: SortingState) => void | - | Callback when sorting changes |
Column-Level Sorting Options:
| Property | Type | Default | Description |
|---|---|---|---|
sortable | boolean | true | Enable/disable sorting for this column |
sortingFn | SortingFn | string | 'auto' | Custom sorting function or built-in function name |
sortDescFirst | boolean | false | Start with descending sort for this column |
invertSorting | boolean | false | Invert the sort order (useful for rankings) |
sortUndefined | 'first' | 'last' | false | -1 | 1 | -1 | Where to place undefined values in sort |
Filtering
NvDatatable provides flexible global filtering capabilities with support for both client-side and server-side filtering modes. Build custom filter UIs using the renderFiltering prop to create search inputs, dropdown filters, date pickers, and more.
Filtering Modes
- Client-Side Filtering: All data is filtered in the browser using a custom filter function
- Server-Side Filtering: Filtering is handled by your API using query parameters
Client-Side Filtering
Best for datasets that are fully loaded in the browser. The table evaluates your custom filter function against all rows instantly.
import { NvDatatable, makeColumn } from '@nova-design-system/nova-react';
import type { Row } from '@tanstack/react-table';
interface Invoice {
id: number;
invoiceNumber: string;
customerName: string;
amount: number;
status: 'paid' | 'pending' | 'overdue';
}
function MyTable() {
const [searchTerm, setSearchTerm] = useState('');
const col = makeColumn<Invoice>();
const columns = [
col({ field: 'invoiceNumber', headerName: 'Invoice #' }),
col({ field: 'customerName', headerName: 'Customer' }),
col({ field: 'amount', headerName: 'Amount' }),
col({ field: 'status', headerName: 'Status' }),
];
// Custom filter function evaluates each row
const customFilterFn = (
row: Row<Invoice>,
columnId: string,
filterValue: unknown
): boolean => {
if (!filterValue || typeof filterValue !== 'string') return true;
const searchLower = filterValue.toLowerCase();
const rowData = row.original;
// Search across multiple fields
return (
rowData.invoiceNumber.toLowerCase().includes(searchLower) ||
rowData.customerName.toLowerCase().includes(searchLower)
);
};
return (
<NvDatatable
columns={columns}
rows={allInvoices}
filtering={{
mode: 'client',
filterState: searchTerm,
onFilterChange: setSearchTerm,
globalFilterFn: customFilterFn,
debounceMs: 300, // Debounce search input
}}
renderFiltering={(api) => (
<div className="mb-4">
<input
type="text"
placeholder="Search invoices..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
<p>Showing {api.filteredRows} of {api.totalRows} invoices</p>
</div>
)}
/>
);
}
Key Points:
- All data must be loaded in the
rowsprop - Your
globalFilterFnevaluates each row against the filter state - Filtering happens instantly with debouncing to prevent excessive re-renders
- Works seamlessly with client-side pagination and sorting
Multi-Criteria Filtering
For complex filtering with multiple inputs, use an object as your filter state:
interface FilterState {
searchTerm: string;
status: string;
minAmount: number;
}
function MyTable() {
const [filterState, setFilterState] = useState<FilterState>({
searchTerm: '',
status: '',
minAmount: 0,
});
const customFilterFn = (
row: Row<Invoice>,
columnId: string,
filterValue: unknown
): boolean => {
if (!filterValue || typeof filterValue !== 'object') return true;
const filter = filterValue as FilterState;
const rowData = row.original;
// Check search term (across multiple fields)
if (filter.searchTerm) {
const searchLower = filter.searchTerm.toLowerCase();
const matchesSearch =
rowData.invoiceNumber.toLowerCase().includes(searchLower) ||
rowData.customerName.toLowerCase().includes(searchLower);
if (!matchesSearch) return false;
}
// Check status filter
if (filter.status && rowData.status !== filter.status) {
return false;
}
// Check amount filter
if (filter.minAmount && rowData.amount < filter.minAmount) {
return false;
}
return true;
};
return (
<NvDatatable
columns={columns}
rows={allInvoices}
filtering={{
mode: 'client',
filterState,
onFilterChange: setFilterState,
globalFilterFn: customFilterFn,
debounceMs: 300,
}}
renderFiltering={(api) => (
<div className="mb-4">
<div className="flex gap-4 mb-4">
<input
type="text"
placeholder="Search..."
value={filterState.searchTerm}
onChange={(e) => setFilterState({
...filterState,
searchTerm: e.target.value
})}
/>
<select
value={filterState.status}
onChange={(e) => setFilterState({
...filterState,
status: e.target.value
})}
>
<option value="">All Statuses</option>
<option value="paid">Paid</option>
<option value="pending">Pending</option>
<option value="overdue">Overdue</option>
</select>
<input
type="number"
placeholder="Min amount"
value={filterState.minAmount}
onChange={(e) => setFilterState({
...filterState,
minAmount: Number(e.target.value)
})}
/>
</div>
<p>Showing {api.filteredRows} of {api.totalRows} invoices</p>
</div>
)}
/>
);
}
Server-Side Filtering
Best for large datasets where filtering is performed by your backend API.
import {
NvDatatable,
makeColumn,
type NvDataTableSortingState
} from '@nova-design-system/nova-react';
interface FilterState {
searchTerm: string;
department: string;
status: string;
}
function MyTable() {
const [filterState, setFilterState] = useState<FilterState>({
searchTerm: '',
department: '',
status: '',
});
const [currentPage, setCurrentPage] = useState(0);
const [pageSize, setPageSize] = useState(10);
const [sortState, setSortState] = useState<NvDataTableSortingState>([]);
// Fetch data from API with filters
const { data, totalCount, isLoading } = useFetchData({
page: currentPage,
pageSize,
filters: filterState,
sort: sortState,
});
const handlePaginationChange = ({ pageIndex, pageSize }) => {
setCurrentPage(pageIndex);
setPageSize(pageSize);
};
return (
<NvDatatable
columns={columns}
rows={data} // Pre-filtered data from API
pagination={{
mode: 'server',
totalRowCount: totalCount,
initialPageSize: 10,
onPaginationChange: handlePaginationChange,
}}
sorting={{
mode: 'server',
sortState,
onSortingChange: (newSort) => {
setSortState(newSort);
setCurrentPage(0); // Reset to page 1 when sorting changes
},
}}
filtering={{
mode: 'server',
filterState,
onFilterChange: (newFilter) => {
setFilterState(newFilter as FilterState);
setCurrentPage(0); // Reset to page 1 when filters change
},
debounceMs: 300, // Debounce API calls
}}
renderFiltering={(api) => (
<div className="mb-4">
<div className="flex gap-4 mb-4">
<input
type="text"
placeholder="Search..."
value={filterState.searchTerm}
onChange={(e) => setFilterState({
...filterState,
searchTerm: e.target.value
})}
/>
<select
value={filterState.department}
onChange={(e) => setFilterState({
...filterState,
department: e.target.value
})}
>
<option value="">All Departments</option>
<option value="Engineering">Engineering</option>
<option value="Sales">Sales</option>
<option value="Marketing">Marketing</option>
</select>
</div>
{isLoading ? (
<p>Loading...</p>
) : (
<p>Showing {totalCount} users {hasActiveFilters && '(filtered)'}</p>
)}
</div>
)}
/>
);
}
Key Points:
- Pass pre-filtered data to
rowsprop - Use
onFilterChangecallback to update filter state and fetch new data - Reset
currentPageto 0 when filters change to show filtered results from the beginning - Parent component manages filter state and data fetching
- Combine with server-side pagination and sorting
Building Query Parameters
When implementing server-side filtering, construct your API query parameters from the filter state:
const fetchData = async (filters: FilterState, page: number, pageSize: number) => {
const params = new URLSearchParams({
_page: String(page + 1),
_per_page: String(pageSize),
});
// Add filters as query parameters
if (filters.searchTerm) {
params.append('_like', filters.searchTerm); // Global search
}
if (filters.department) {
params.append('department', filters.department); // Exact match
}
if (filters.status) {
params.append('status', filters.status);
}
if (filters.dateRange) {
params.append('createdAt_gte', filters.dateRange.start);
params.append('createdAt_lte', filters.dateRange.end);
}
const response = await fetch(`/api/users?${params.toString()}`);
return response.json();
};
Filter UI with Visual Feedback
Enhance user experience by showing active filters as dismissible chips:
function MyTable() {
const [filterState, setFilterState] = useState({
searchTerm: '',
status: '',
department: '',
});
const hasActiveFilters =
filterState.searchTerm ||
filterState.status ||
filterState.department;
const clearAllFilters = () => {
setFilterState({
searchTerm: '',
status: '',
department: '',
});
};
return (
<NvDatatable
columns={columns}
rows={data}
filtering={{
mode: 'client',
filterState,
onFilterChange: setFilterState,
globalFilterFn: customFilterFn,
}}
renderFiltering={(api) => (
<div className="mb-4">
{/* Filter Controls */}
<div className="flex gap-4 mb-4">
<input
type="text"
placeholder="Search..."
value={filterState.searchTerm}
onChange={(e) => setFilterState({
...filterState,
searchTerm: e.target.value
})}
/>
<select
value={filterState.status}
onChange={(e) => setFilterState({
...filterState,
status: e.target.value
})}
>
<option value="">All Statuses</option>
<option value="active">Active</option>
<option value="inactive">Inactive</option>
</select>
</div>
{/* Active Filter Chips */}
{hasActiveFilters && (
<div className="flex items-center gap-2 mb-4">
<span className="text-sm font-medium">Filters applied:</span>
{filterState.status && (
<NvBadge
label={`Status: ${filterState.status}`}
color="information"
dismissible
onCloseClicked={() => setFilterState({
...filterState,
status: ''
})}
/>
)}
{filterState.department && (
<NvBadge
label={`Department: ${filterState.department}`}
color="information"
dismissible
onCloseClicked={() => setFilterState({
...filterState,
department: ''
})}
/>
)}
<button onClick={clearAllFilters}>
Clear all filters
</button>
</div>
)}
{/* Results Count */}
<div className="text-sm">
Showing <strong>{api.filteredRows}</strong> of{' '}
<strong>{api.totalRows}</strong> results
</div>
</div>
)}
/>
);
}
Filtering Configuration Reference
Global Filtering Config (filtering prop):
| Property | Required | Type | Default | Description |
|---|---|---|---|---|
mode | ✅ | 'client' | 'server' | - | Filtering mode |
filterState | - | any | - | Your custom filter state (string, object, array, etc.) |
onFilterChange | - | (newFilter: any) => void | - | Callback when filter state changes |
debounceMs | - | number | 300 | Debounce delay in milliseconds for filter changes (works in both client and server modes) |
| Client-side specific | ||||
globalFilterFn | - | FilterFn | - | Custom filter function to evaluate rows |
FilterFn Type:
type FilterFn<T> = (
row: Row<T>,
columnId: string,
filterValue: unknown
) => boolean
The function receives:
row: The complete row object with access torow.originalfor raw datacolumnId: The column ID being filtered (useful for column-specific filters)filterValue: Your currentfilterStatevalue
Return true to include the row, false to filter it out.
Filtering API Reference
The renderFiltering prop receives an API object with these properties:
| Property | Type | Description |
|---|---|---|
filteredRows | number | Count of rows after filtering |
totalRows | number | Total row count before filtering |
Best Practices
When to Use Client vs Server Filtering:
- Client-side: Datasets under a few thousand rows, instant feedback desired, all data available
- Server-side: Large datasets (10,000+ rows), filtered data must come from database, need server-side validation
Debouncing Search Inputs:
filtering={{
mode: 'client',
filterState: searchTerm,
onFilterChange: setSearchTerm,
debounceMs: 300, // Wait 300ms after typing stops before filtering
}}
This prevents excessive filtering on every keystroke, improving performance and reducing API calls.
Resetting Pagination: Always reset to page 1 when filters change to avoid showing empty results:
onFilterChange: (newFilter) => {
setFilterState(newFilter);
setCurrentPage(0); // Reset to first page
}
Combining with Pagination and Sorting: Filtering works seamlessly with both pagination and sorting:
- Client-side: All three operations happen in the browser on the full dataset
- Server-side: Send filter, pagination, and sort parameters together in API request
TypeScript Type Safety: Define a strict interface for your filter state for better type checking:
interface FilterState {
searchTerm: string;
status: 'active' | 'inactive' | '';
dateRange: { start: string; end: string } | null;
}
const [filterState, setFilterState] = useState<FilterState>({
searchTerm: '',
status: '',
dateRange: null,
});
Row Selection
NvDatatable supports both single and multiple row selection with checkbox UI, persistent selection across pagination, and optional automatic deselection of filtered-out rows when using client-side filtering.
Configuration
Row selection is configured through the selection prop:
| Property | Type | Description |
|---|---|---|
mode | 'none' | 'single' | 'multiple' | Selection mode (default: 'none') |
getRowId | (row: T) => string | Required function to extract unique row identifier |
selectedRowIds | Set<string> | Currently selected row IDs (controlled — see Controlled vs Uncontrolled Selection) |
initialSelectedRowIds | Set<string> | Seeds selection on first render only (uncontrolled). Ignored when selectedRowIds is set. |
onSelectionChange | (selectedRowIds: Set<string>) => void | Callback when selection changes |
enableSelectAll | boolean | Enable select-all checkbox in header (multiple mode only, default: true) |
deselectOnFilter | boolean | Deselect filtered-out rows during client-side filtering (default: true) |
checkboxColumnWidth | number | Checkbox column width in pixels (default: 48) |
Basic Single Row Selection
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
<NvDatatable
columns={columns}
rows={rows}
selection={{
mode: 'single',
getRowId: (row) => row.id.toString(),
selectedRowIds: selectedIds,
onSelectionChange: (ids) => setSelectedIds(new Set(ids)),
}}
/>
Multiple Row Selection
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
<NvDatatable
columns={columns}
rows={rows}
selection={{
mode: 'multiple',
getRowId: (row) => row.id.toString(),
selectedRowIds: selectedIds,
onSelectionChange: (ids) => setSelectedIds(new Set(ids)),
enableSelectAll: true,
}}
/>
Controlled vs Uncontrolled Selection
selection supports two modes, mirroring the sorting API:
- Controlled — provide
selectedRowIds(and usuallyonSelectionChange). The parent owns the truth: the component re-syncs fromselectedRowIdswhenever it changes. Use this when other UI needs to react to selection between clicks. - Uncontrolled — provide
initialSelectedRowIdsinstead. The component owns the state internally and the parent doesn't need to participate.onSelectionChangeis still available if you want to observe changes without taking ownership.
// Uncontrolled — start with no selection, let users select freely
<NvDatatable
columns={columns}
rows={rows}
selection={{
mode: 'multiple',
getRowId: (row) => row.id.toString(),
initialSelectedRowIds: new Set(), // optional, omit for empty
}}
/>
// Uncontrolled with seed — pre-select a few rows on mount
<NvDatatable
columns={columns}
rows={rows}
selection={{
mode: 'multiple',
getRowId: (row) => row.id.toString(),
initialSelectedRowIds: new Set(['1', '3']),
onSelectionChange: (ids) => console.log('selection changed', ids),
}}
/>
When picking between the two: prefer uncontrolled unless the parent actually needs to render based on the current selection. Controlled state requires keeping selectedRowIds in sync with onSelectionChange on every render.
Selection with Filtering
When using client-side filtering (where NvDatatable filters rows locally), rows that become filtered out are automatically deselected by default. Disable this behavior with deselectOnFilter: false.
In server-side filtering mode, this automatic deselection is not applied. If you want selection to change when filters change, handle it in your own data-fetching and/or onSelectionChange logic.
<NvDatatable
columns={columns}
rows={rows}
filtering={{
filterState,
globalFilterFn,
}}
selection={{
mode: 'multiple',
getRowId: (row) => row.id.toString(),
selectedRowIds: selectedIds,
onSelectionChange: (ids) => setSelectedIds(new Set(ids)),
deselectOnFilter: true,
}}
/>
Important Notes
getRowIdis required wheneverselection.modeis not'none'.- Use controlled state (
selectedRowIds+onSelectionChange) for predictable behavior. - Selection persists across pagination when row IDs remain stable.
- For large datasets, keep row IDs deterministic and unique across pages.
Row Click Actions
Use onRowClick to react to full-row clicks (for example, open a details panel, navigate to another page, or trigger analytics) while still allowing checkbox-based selection.
Callback Payload
onRowClick receives NvDatatableRowClickEventArgs<T> with:
row: The full row data objectrowIndex: Zero-based index in the current visible rows
<NvDatatable
columns={columns}
rows={rows}
onRowClick={({ row, rowIndex }) => {
console.log('Clicked row', rowIndex + 1, row);
}}
selection={{
mode: 'multiple',
getRowId: (row) => row.id.toString(),
selectedRowIds: selectedIds,
onSelectionChange: (ids) => setSelectedIds(new Set(ids)),
enableSelectAll: true,
}}
/>
Interaction Behavior
- Clicking a row triggers
onRowClick. - Clicking a selection checkbox updates selection and does not trigger
onRowClick. - Keyboard activation (
Enter/Space) on a focused row triggersonRowClick. - Keyboard activation on a focused checkbox updates selection only.
Horizontal Scrolling
For tables with many columns or wide content, enable horizontal scrolling by adding CSS classes:
<NvDatatable
columns={columns}
rows={data}
className="block overflow-x-auto"
/>
Sticky Header
Enable sticky headers to keep column headers visible when scrolling through long tables. This is especially useful for tables with many rows where you want to maintain context of what each column represents.
<NvDatatable
columns={columns}
rows={data}
stickyHeader={true}
/>