@tranz-rath/components
v1.0.5
Published
Client and server data grid wrappers built on MUI.
Readme
@tranz-rath/components
Client- and server-side wrappers around MUI X Data Grid Premium plus Autocomplete helpers with sensible defaults for fetching, pagination, sorting, filtering, and quick toolbar wiring.
- Built for React 18+ / Next 13+ projects using
@mui/x-data-grid-premium. - Client grid can auto-fetch and normalize responses out of the box.
- Server grid streams rows through the MUI
dataSourceAPI with URL query syncing for deep-linkable states. - Client + server autocomplete components handle option fetching, value mapping, and quick wiring to forms.
Installation
npm install @tranz-rath/components @mui/material @mui/x-data-grid-premium @emotion/react @emotion/styledPeer dependencies: react, react-dom, and (optionally) next if you use the server grid inside Next.js.
Components
ClientDataGrid
A client-side data grid that can either render provided rows or fetch them from an API.
import { ClientDataGrid } from "@tranz-rath/components";
const columns = [
{ field: "id", headerName: "ID", width: 80 },
{ field: "name", headerName: "Name", flex: 1 },
];
export default function UsersGrid() {
return (
<ClientDataGrid
apiUrl="/api/users" // omit to use the `rows` prop instead
dataPath="data.items" // where rows live in the JSON (default: "data")
columns={columns} // optional; auto-generated from first row if missing
pageSizeOptions={[10, 25, 50]}
showToolbar // enables quick filter + toolbar
onFetchSuccess={(rows, payload) => console.log(rows.length)}
/>
);
}Key props:
apiUrl: When set (androwsis undefined) the grid fetches JSON on mount.requestInit: Extrafetchoptions (headers, method, etc.).dataPath: Dot path inside the JSON to locate the rows; falls back to common keys (data,rows,items,results).transformResponse(payload): Custom mapper that must return an array of rows.getRowId: Supply if your rows do not include anid; otherwise indexes are used.slots/slotProps: Passed directly toDataGridPremium; toolbar shows quick filter by default.
You can also provide rows directly; apiUrl is ignored when rows is set.
ServerDataGrid
A server-mode grid wired for the MUI dataSource API with optional URL query syncing (page, size, sort, filters) for shareable links.
import { ServerDataGrid } from "@tranz-rath/components";
const columns = [
{ field: "name", headerName: "Name", flex: 1 },
{ field: "role", headerName: "Role", flex: 1 },
];
export default function UsersGrid() {
return (
<ServerDataGrid
apiUrl="/api/users"
columns={columns}
rowCountPath="meta.total" // where total count lives (optional)
dataPath="data" // where rows live (default: "data")
pageSizeOptions={[10, 25, 50, 100]}
syncQueryParams // keep page/sort/filter in the URL (default: true)
buildQueryParams={(params) => {
// params = { paginationModel, sortModel, filterModel, start, end }
return {
start: params.start,
end: params.end,
sortColumn: params.sortModel?.[0]?.field,
sortDirection: params.sortModel?.[0]?.sort,
search: params.filterModel?.quickFilterValues?.join(" "),
};
}}
/>
);
}Default query behavior (if buildQueryParams is not provided):
- Pagination:
pageandpageSizequery params (0-based page index). - Sorting:
sortColumn+sortDirection(asc/desc). - Filtering: single
filterColumn,filterOperator,filterValueper filter item. - Quick filter:
search.
Response expectations:
- Rows are read from
dataPath(defaults todata), or fromdata,rows,items, orresults. - Total row count is read from
rowCountPath, or fromrowCount,total,totalCount,count, orpagination.total. - You may override with
transformResponse(payload, params)returning{ rows, rowCount? }.
URL synchronization:
- Controlled by
syncQueryParams(defaulttrue); capturespage,pageSize,sortField,sortDir,filters(JSON), andsearch. - If you pass controlled models (
paginationModel,sortModel,filterModel), the grid respects them and still updates the URL unlesssyncQueryParamsisfalse.
Styling:
sxis merged with a default bordered layout.slots/slotPropsare passed through; toolbar quick filter is enabled by default.
ClientAutocomplete
Lightweight autocomplete that accepts static options, maps values by id/label (customizable), and handles controlled/uncontrolled values cleanly.
import { ClientAutocomplete } from "@tranz-rath/components";
const options = [
{ id: 1, label: "Alice" },
{ id: 2, label: "Bob" },
];
export default function UserPicker() {
return (
<ClientAutocomplete
label="User"
id="user"
name="user"
options={options}
value={2}
onChange={(event, value) => console.log(value)} // value -> option.id (or array for multiple)
loadFirst // auto-select first option when empty
multiple={false}
/>
);
}Key props:
options: Array of options; expects{ [valueKey], [labelKey] }(defaultsid/label).value: Can be an id, an option object, or an array (whenmultiple).onChange(event, mappedValue): Receives the mapped id (or array of ids).onOptionsLoad(map): Map ofvalueKey -> labelKeyemitted when options change.loadFirst: Auto-picks the first option when no value is set.renderInput: Custom input render; defaults toTextFieldwith a spinner placeholder whenloadingis true.
ServerAutocomplete
Autocomplete that fetches options from an API with optional server-side search, debounce, and default select endpoints.
import { ServerAutocomplete } from "@tranz-rath/components";
export default function CityPicker() {
return (
<ServerAutocomplete
label="City"
id="city"
name="city"
apiUrl="/api/cities" // or set `select="cities"` to hit /api/select/cities
dataPath="data.options" // where options live in the JSON (default: "options")
serverSearch // appends `?q=` as you type (configurable via `searchParam`)
minSearchLength={2}
debounceMs={250}
onChange={(event, value) => console.log(value)} // value -> option.id (or array)
loadFirst
/>
);
}Key props:
apiUrlorselect: URL to fetch options; whenselectis provided it calls/api/select/{select}.dataPath: Dot path to options array; falls back tooptions.transformResponse(payload): Optional mapper returning an array of options.serverSearch: Enable server-side filtering; sendssearchParam(defaultq) withinputValue.minSearchLength+debounceMs: Guardrails for server search.refresh: Any value change triggers a refetch (use for manual invalidation).valueKey/labelKey: Which keys identify and display options; defaultsid/label.loadFirst: Auto-select the first option after fetch when no value is set.renderInput: Custom input renderer; defaults to aTextFieldwith spinner adornment.
fetcher
Wrapper around fetch that applies a proxy host and redirects to / when the response is unauthorized (401/403).
import { fetcher } from "@tranz-rath/components";
const response = await fetcher("/api/users", { method: "GET" });
const data = await response.json();Proxy host resolution order (first non-empty wins):
globalThis.RATH_PROXY_HOSTat runtime (e.g., set before rendering in the browser).process.env.RATH_PROXY_HOSTorprocess.env.NEXT_PUBLIC_RATH_PROXY_HOSTat build/runtime.- The packaged
.PROXY.jsdefault.
Examples:
// Browser runtime
window.RATH_PROXY_HOST = "https://proxy.example.com";
// Next.js / Node build
process.env.NEXT_PUBLIC_RATH_PROXY_HOST = "https://proxy.example.com";Configure the proxy host by setting the default export in .PROXY.js, for example:
// .PROXY.js
const PROXY_HOST = "https://proxy.example.com";
export default PROXY_HOST;Local development
This package ships compiled ESM; no build step is required here. To test locally in an app:
- Run
npm packin this repo. - In your app, install the tarball (
npm install ../rath-components-*.tgz) and import the components.
License
ISC © Tranz Technologies
