@hari_digitus/form-controls
v4.0.12
Published
Reusable table primitives for the FCI-OA frontend: a wrapper around PrimeReact's `DataTable` (`ReusableDataTable`) and a custom, PrimeReact-styled `TablePaginator`. Built to swap in for PrimeReact's built-in paginator while giving full control over mark
Readme
@digitus-fci-oa/table-components
Reusable table primitives for the FCI-OA frontend: a wrapper around PrimeReact's DataTable
(ReusableDataTable) and a custom, PrimeReact-styled TablePaginator. Built to swap in for
PrimeReact's built-in paginator while giving full control over markup and behavior.
Contents
- Installation
- Components
- Full usage example
- Known gotchas
- Troubleshooting
- Contributing / local development
Installation
npm install @digitus-fci-oa/table-componentsPeer dependencies (must already be installed in the consuming app):
npm install react react-dom primereactComponents
TablePaginator
A custom pagination bar: first/prev/next/last controls, a "jump to page" input, a
rows-per-page <select>, and a results summary (Showing X of Y results).
import { TablePaginator } from "@digitus-fci-oa/table-components";Props
| Prop | Type | Required | Description |
|------------------------|-----------------------------------------------------|----------|-------------------------------------------------------------------------------|
| currentPage | number | ✅ | 1-based current page number. |
| rows | number | ✅ | Rows per page. |
| totalRecords | number | ✅ | Total number of records across all pages. |
| inputValue | number \| string | ✅ | Controlled value for the "jump to page" input. |
| onPageChange | (e: PaginatorPageChangeEvent) => void | ✅ | Fired on first/prev/next/last click and on rows-per-page change. |
| onRowsChange | (e: React.ChangeEvent<HTMLSelectElement>) => void | ✅ | Fired when the rows-per-page <select> changes. Receives the raw DOM event, not a number — see gotchas. |
| onPageInput | (e: React.ChangeEvent<HTMLInputElement>) => void | ✅ | Controlled onChange for the page-jump input. |
| onPageKeyDown | (e: React.KeyboardEvent<HTMLInputElement>) => void | ✅ | Typically used to detect Enter and commit the page jump. |
| onPageBlur | () => void | ✅ | Typically used to commit/validate the page jump on blur. |
| rowsPerPageOptions | number[] | ❌ | Defaults to [10, 25, 50, 100]. |
| className | string | ❌ | Extra classes merged onto the root container. |
| datatestid | string | ❌ | data-testid on the root container, for tests. |
PaginatorPageChangeEvent
interface PaginatorPageChangeEvent {
first: number; // index of the first record on the new page (0-based)
rows: number; // rows per page
page: number; // 0-based page index
pageCount: number; // total number of pages
}Note:
pageis 0-based to match PrimeReact's paginator convention, even thoughcurrentPage(the prop you pass in) is 1-based.
ReusableDataTable
A typed wrapper around primereact/datatable that supports two sort modes and a
declarative columns config instead of hand-written <Column> children.
import { DataTable } from "@digitus-fci-oa/table-components";Exported as
DataTablefrom the package, backed by theReusableDataTableimplementation.
Props
| Prop | Type | Default | Description |
|--------------------|-----------------------------------------------|------------|-------------------------------------------------------------------------------|
| value | T[] | — | Row data. |
| dataKey | string | "id" | Unique row identifier field. |
| lazy | boolean | true | If true, the table assumes value is a full dataset and slices it client-side using first/rows. |
| first | number | 0 | Index of the first row to display (used when lazy is true). |
| rows | number | 10 | Rows per page (used when lazy is true). |
| totalRecords | number | — | Total record count, passed through to PrimeReact for internal bookkeeping. |
| onPage | (event: DataTablePageEvent) => void | — | PrimeReact page-change callback, passed straight through. |
| sortField | string | — | External sort field. Providing onSort switches the table to external/controlled sort mode. |
| sortOrder | 1 \| -1 \| null | — | External sort order, paired with sortField. |
| onSort | (event: DataTableSortEvent) => void | — | If provided, disables the built-in useTableSort hook and defers sorting to the parent. |
| scrollHeight | string | "380px" | Passed to PrimeReact's scrollHeight. |
| tableStyle | CSSProperties | — | Merged into the table's inline style. |
| className | string | — | Extra classes merged onto the table. |
| columns | ColumnDef<T>[] | — | Declarative column definitions (see below). |
| checkboxHeader | () => ReactNode | — | Renders a frozen checkbox column header. Requires checkboxBody too. |
| checkboxBody | (rowData: T) => ReactNode | — | Renders per-row checkbox content. |
| actionHeader | () => ReactNode | — | Renders a frozen, right-aligned action column header. |
| actionBody | (rowData: T) => ReactNode | — | Renders per-row action content (buttons, menus, etc.). |
| emptyMessage | ReactNode | built-in | Custom "no data" state. |
| renderKey | string \| number | — | Passed as React key on the underlying DataTable to force a full remount. |
ColumnDef<T>
interface ColumnDef<T = any> {
field?: string;
header: string | (() => ReactNode);
body?: (rowData: T) => ReactNode;
style?: CSSProperties;
sortable?: boolean;
frozen?: boolean;
alignFrozen?: "left" | "right";
headerClassName?: string;
bodyClassName?: string;
hidden?: boolean; // filtered out before render — use for toggleable/configurable columns
}Sort modes
- Internal (default): omit
onSort. The table manages its ownsortField/sortOrderstate via theuseTableSorthook and sortsvalueclient-side. - External: pass
onSort(typically alongsidesortField/sortOrderfrom parent state). The parent becomes responsible for re-fetching or re-sortingvalue— the component will not sort on its own in this mode.
Full usage example
Adapted from the supplier list screen (SupplierTable.tsx):
import React, { useEffect, useState } from "react";
import { DataTable, TablePaginator } from "@digitus-fci-oa/table-components";
import type { PaginatorPageChangeEvent } from "primereact/paginator";
function SupplierTable({ first, rows, totalRecords, suppliers, columnConfigs, onPageChange }: any) {
const [currentPage, setCurrentPage] = useState(Math.floor(first / rows) + 1);
const [inputValue, setInputValue] = useState<number | string>(currentPage);
useEffect(() => {
const page = Math.floor(first / rows) + 1;
setCurrentPage(page);
setInputValue(page);
}, [first, rows]);
const totalPages = Math.ceil(totalRecords / rows);
const handlePageChange = (e: PaginatorPageChangeEvent) => {
setCurrentPage(e.page + 1);
setInputValue(e.page + 1);
onPageChange?.(e);
};
// ⚠️ onRowsChange receives the raw <select> change event, not a number.
const handleRowsChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
const newRows = Number(e.target.value);
setCurrentPage(1);
setInputValue(1);
onPageChange?.({ first: 0, rows: newRows, page: 0 } as PaginatorPageChangeEvent);
};
const goToPage = (page: number) => {
if (page >= 1 && page <= totalPages) {
setCurrentPage(page);
onPageChange?.({ first: (page - 1) * rows, rows, page: page - 1 } as PaginatorPageChangeEvent);
} else {
setInputValue(currentPage);
}
};
return (
<div>
<DataTable
value={suppliers}
dataKey="id"
columns={columnConfigs}
totalRecords={totalRecords}
scrollHeight="calc(100dvh - 200px)"
/>
<TablePaginator
currentPage={currentPage}
rows={rows}
totalRecords={totalRecords}
inputValue={inputValue}
onPageChange={handlePageChange}
onRowsChange={handleRowsChange}
onPageInput={(e) => setInputValue(e.target.value)}
onPageKeyDown={(e) => e.key === "Enter" && goToPage(Number(inputValue))}
onPageBlur={() => goToPage(Number(inputValue))}
/>
</div>
);
}
export default SupplierTable;Known gotchas
onRowsChangetakes an event, not a number.TablePaginator's rows-per-page control is a native<select>, so itsonChangehandler is typed(e: React.ChangeEvent<HTMLSelectElement>) => void. A common mistake is writing a handler like(rows: number) => voidand casting it to satisfy TypeScript (as unknown as (e: ...) => void). Avoid the cast — read the value offe.target.valueinstead:const handleRowsChange = (e: React.ChangeEvent<HTMLSelectElement>) => { const newRows = Number(e.target.value); // ... };Type errors after editing this package locally. If you change a prop signature in the package source (e.g.
TablePaginator'sonRowsChange) but the consuming app still complains about the old signature, the package needs to be rebuilt and reinstalled — the consuming app is compiling against the publisheddist/*.d.ts, not the live source:# inside the table-components package npm run build # inside the consuming app npm installrowsmust be one ofrowsPerPageOptions.TablePaginatorrenders<select value={rows}>. If therowsvalue passed in isn't present inrowsPerPageOptions, the browser will show a blank/unmatched selection. Make sure the initialrowsstate in the parent is one of the configured options (default:[10, 25, 50, 100]), or pass a matching customrowsPerPageOptionsarray.Resetting to page 1 on rows-per-page change. Changing rows-per-page while on a later page can leave
currentPagepointing past the newtotalPages. The example above resets to page 1 (first: 0, page: 0) on every rows-per-page change — keep this behavior unless you have a reason to preserve position.
Troubleshooting
TypeError: Cannot read properties of undefined (reading 'filter')
This error is not produced by TablePaginator or ReusableDataTable — neither
component calls .filter() on external data internally in a way that would surface this
(the only .filter() calls inside this package are on columns arrays that are guaranteed
to exist by their prop types).
If you see this error triggered from a loadUserAccount / fetchAndFilterSuppliers-style
call chain (e.g. after changing rows-per-page or page), it means an async data-fetching
handler upstream (in your app, not this package) is calling .filter() on a value that
hasn't loaded yet — typically:
- A user/account object or one of its fields (
roles,permissions,accounts, etc.) isundefinedat the time of the call, because the fetch that provides it hasn't resolved. onPageChangetriggers a re-fetch (fetchAndFilterSuppliers) before some prerequisite state (e.g. the logged-in user's account) has finished loading.
How to fix:
- Guard the
.filter()call with a default:(someValue ?? []).filter(...). - Or ensure
loadUserAccountis awaited/resolved beforefetchAndFilterSuppliersruns. - Or initialize the relevant state with an empty array/object instead of
undefined.
This fix lives in your application code (loadUserAccount / fetchAndFilterSuppliers),
not in this package.
Contributing / local development
# install deps
npm install
# build the package (regenerates dist/ and .d.ts files)
npm run build
# type-check only
npx tsc --noEmitWhen testing local changes against a consuming app without publishing:
# in this package
npm link
# in the consuming app
npm link @digitus-fci-oa/table-componentsRemember to npm run build after every source change — linked packages still resolve
against dist/, not src/, unless your build config says otherwise.
