dynamic-table-builder
Version:
A dynamic table library with backend-driven configuration
284 lines (227 loc) • 12 kB
Markdown
# Dynamic Table Builder
A powerful and flexible React table library that supports backend-driven configuration, built on top of Ant Design. This document provides a comprehensive guide to the `DynamicTable` component and its JSON configuration structure.
## Features
- **Backend-Driven Configuration**: Define table structure, filters, sorting, and more from a JSON object, usually fetched from a backend.
- **Global and Column-Level Filters**: Supports various filter types like search, select, and date range.
- **Sortable Columns**: Enable sorting on specified columns.
- **Pagination**: Complete pagination support, configurable from the JSON.
- **State Persistence**: Persist table state (filters, sorting, pagination) to `localStorage`.
- **Custom Rendering**: Render cell content as links, statuses with colors, formatted dates, and numbers.
- **Action Buttons**: Configurable action buttons for functionalities like Export and Refresh.
- **Row Selection**: Support for checkbox-based row selection.
## Installation
First, make sure you have the required peer dependencies installed:
```bash
npm install antd @ant-design/icons dayjs
```
Then, install the library:
```bash
npm install dynamic-table-builder
```
## How to Use
Here's a basic example of how to integrate the `DynamicTable` component.
```tsx
import React from 'react';
import DynamicTable from 'dynamic-table-builder';
import 'dynamic-table-builder/dist/index.css'; // Don't forget to import styles
const YourComponent = () => {
// This config would typically come from an API
const tableConfiguration = { /* ... Your JSON config ... */ };
const handleDataFetch = async (params) => {
console.log('Fetching data with params:', params);
// 'params' will contain { pagination, filters, sorter }
// Fetch data from your API and return it in the expected format.
// Example:
// const response = await yourApi.getData(params);
// return { data: response.items, pagination: { totalCount: response.total } };
return Promise.resolve({ data: [], pagination: { totalCount: 0 } });
};
const handleExport = async (params) => {
console.log('Exporting data with params:', params);
// 'params' will contain { filters, sort }
// Call your API to get the export data (e.g., a CSV blob).
// Example:
// const blob = await yourApi.exportData(params);
// return blob;
return Promise.resolve(new Blob(["Success"]));
};
return (
<DynamicTable
config={tableConfiguration}
onDataFetch={handleDataFetch}
onExport={handleExport}
className="custom-table-class"
/>
);
};
export default YourComponent;
```
## JSON Configuration Structure
The `DynamicTable` is configured through a single JSON object. Here is the breakdown of its main properties.
```json
{
"data": [],
"columns": [],
"pagination": {},
"tableConfig": {},
"tableFeatures": {}
}
```
- `data`: An array of objects, where each object represents a row in the table. While it can be provided initially, the component is designed to fetch data dynamically via the `onDataFetch` prop.
- `columns`: (Required) An array of objects defining the table's columns.
- `pagination`: Configuration for the table's pagination.
- `tableConfig`: General table settings like title, action buttons, and global filters.
- `tableFeatures`: Enables or configures special features like row selection and state management.
---
### `columns`
Each object in the `columns` array defines a column.
| Key | Type | Description |
|---|---|---|
| `title` | `string` | The text displayed in the column header. |
| `key` | `string` | A unique identifier for the column. This should match a key in the `data` objects. |
| `width`| `number` | The width of the column in pixels. |
| `sortable`| `boolean`| If `true`, the column can be sorted. |
| `render` | `object` | Defines how to render the data in this column's cells. See **Render Configuration** below. |
| `filter` | `object` | Defines a filter for this column. See **Column Filter Configuration** below. |
| `fixed` | `'left' \| 'right'` | Fixes the column to the left or right side of the table. |
#### Render Configuration (`render`)
| Key | Type | Description |
|---|---|---|
| `type` | `string` | The render type. Can be `text`, `link`, `status`, `datetime`, or `number`. |
| `urlTemplate` | `string` | For `type: 'link'`. A template for the URL. Use `{key}` to insert data from the row (e.g., `/users/{id}`). |
| `urlType` | `'internal' \| 'external'` | For `type: 'link'`. `'internal'` opens in the same tab, `'external'` opens in a new tab. Defaults to `'internal'`. |
| `colorMapping`| `object` | For `type: 'status'`. Maps cell values to colors (e.g., `{"active": "success", "inactive": "error"}`). |
| `textMapping` | `object` | For `type: 'status'`. Maps cell values to display text (e.g., `{"PRS_PENDING": "Pending"}`). |
| `format` | `string` | For `type: 'datetime'`, it's a date format string (e.g., `DD-MM-YYYY HH:mm:ss`). For `type: 'number'`, it's the number of decimal places. |
#### Column Filter Configuration (`filter`)
| Key | Type | Description |
|---|---|---|
| `type` | `string` | The filter type. Can be `search` or `select`. |
| `placeholder`| `string` | Placeholder text for the filter input. |
| `mode` | `string` | For `type: 'select'`. Set to `'multiple'` to allow multiple selections. |
| `options`| `array` | For `type: 'select'`. An array of `{ label: string, value: any }` objects. |
| `validation`| `object` | For `type: 'search'`. Validation rules, e.g., `{"minChars": 3}`. Currently informational. |
---
### `pagination`
Configures the table's pagination controls.
| Key | Type | Description |
|---|---|---|
| `pageSize` | `number` | The default number of items per page. |
| `pageSizeOptions` | `number[]`| An array of numbers for the page size selector (e.g., `[10, 20, 50]`). |
| `showQuickJumper`| `boolean` | If `true`, shows an input field to jump to a specific page. |
| `showTotal` | `boolean` | If `true`, displays the total number of items. |
| `position` | `string[]` | An array specifying the position of the pagination controls (e.g., `['bottomRight']`). |
| `showSizeChanger`| `boolean` | If `true`, allows the user to change the page size. |
| `totalCount` | `number` | The total number of items available, which is used to calculate the number of pages. This is usually returned from the API. |
| `requestParams`| `object` | Maps the table's internal pagination state to keys for the API request (e.g., `{"page": "pageNumber", "pageSize": "pageSize"}`). |
---
### `tableConfig`
General table configuration.
| Key | Type | Description |
|---|---|---|
| `title` | `string` | The title displayed above the table. |
| `defaultPageSize`| `number` | Default page size if not specified in `pagination`. |
| `actionButtons` | `object[]` | An array of action buttons. See **Action Button Configuration** below. |
| `globalFilters` | `object[]` | An array of global filters. See **Global Filter Configuration** below. |
| `exportFileName`| `string` | The default filename for exports (e.g., 'data.csv'). |
#### Action Button Configuration
| Key | Type | Description |
|---|---|---|
| `key` | `string` | A unique key. Pre-defined keys `export`, `refresh`, and `clearFilters` have built-in functionality. |
| `title` | `string` | The button's text. |
| `icon` | `string` | The name of an Ant Design icon to display. |
| `iconSource`| `'internal'` | Specifies that the icon is from Ant Design. |
| `type` | `string` | Ant Design button type (`primary`, `default`, etc.). |
| `enabled` | `boolean` | Whether the button is enabled. |
| `position` | `'left' \| 'right'` | Positions the button on the left or right side of the action bar. Defaults to `left`. |
| `onClick` | `function` | Custom click handler. If provided, this overrides default behavior for keys like `export`. |
#### Global Filter Configuration
| Key | Type | Description |
|---|---|---|
| `key` | `string` | A unique key for the filter. |
| `type` | `string` | The filter type: `dateRange`, `select`, or `search`. |
| `title` | `string` | A label displayed for the filter. |
| `placeholder`| `string` | Placeholder text for the filter input. |
| `required` | `boolean` | For `type: 'dateRange'`, if a date range is mandatory. |
| `showTime` | `boolean` | For `type: 'dateRange'`, includes a time picker. |
| `format` | `string` | For `type: 'dateRange'`, the date format (e.g., `DD-MM-YYYY`). |
| `presets` | `object[]`| For `type: 'dateRange'`, predefined date ranges like "Today" or "This Month". |
| `mode` | `string` | For `type: 'select'`, set to `multiple` for multi-select. |
| `options` | `object[]`| For `type: 'select'`, an array of `{ label: string, value: any }` objects. |
| `defaultValue` | `any` | Default value for the filter when the table loads. For date ranges, use dayjs objects: `[dayjs().subtract(30, 'days'), dayjs()]`. For selects, use string or array of strings. |
| `position` | `'left' \| 'right'`| Positions the filter on the left or right. Defaults to the left. |
#### Setting Default Values for Global Filters
You can set default values for any global filter using the `defaultValue` property:
```typescript
// Date Range - Last 30 days
{
key: 'dateRange',
type: 'dateRange',
title: 'Date Range',
defaultValue: [
dayjs().subtract(30, 'days'), // Start date
dayjs() // End date
]
}
// Single Select - Default to specific value
{
key: 'status',
type: 'select',
title: 'Status',
options: [
{ label: 'Active', value: 'ACTIVE' },
{ label: 'Inactive', value: 'INACTIVE' }
],
defaultValue: 'ACTIVE'
}
// Multi-Select - Default to multiple values
{
key: 'roles',
type: 'select',
mode: 'multiple',
title: 'Roles',
options: [
{ label: 'Admin', value: 'ADMIN' },
{ label: 'User', value: 'USER' }
],
defaultValue: ['ADMIN', 'USER']
}
// Search - Default search term
{
key: 'search',
type: 'search',
title: 'Search',
defaultValue: 'john'
}
```
---
### `tableFeatures`
Enables or configures special table features.
| Key | Type | Description |
|---|---|---|
| `rowKey` | `string` | The unique identifier field for each row in the `data` array (e.g., `id`, `prsNumber`). This is crucial for selection and performance. |
| `stateManagement` | `object` | Configures state persistence. See **State Management Configuration** below. |
| `rowSelection`| `object` | Configures row selection. See **Row Selection Configuration** below. |
#### State Management Configuration
| Key | Type | Description |
|---|---|---|
| `enabled` | `boolean` | If `true`, enables state persistence. |
| `storageKey`| `string` | The key to use for storing the table's state in `localStorage`. |
| `persistColumns`| `boolean` | If `true`, persists column visibility and order (future feature). |
| `persistFilters`| `boolean` | If `true`, persists active filters. |
| `persistSort`| `boolean` | If `true`, persists the current sorting. |
| `persistPagination`| `boolean` | If `true`, persists the current page number and size. |
#### Row Selection Configuration
| Key | Type | Description |
|---|---|---|
| `enabled` | `boolean` | If `true`, enables row selection. |
| `type` | `'checkbox' \| 'radio'` | The type of selection. |
## Component Props
| Prop | Type | Description |
|---|---|---|
| `config` | `object` | The main JSON configuration object for the table. |
| `onDataFetch` | `(params) => Promise<{ data: any[], pagination?: { totalCount: number } }>` | A function that is called to fetch table data. It receives `pagination`, `filters`, and `sorter` info and should return the data and total count. |
| `onExport`| `(params) => Promise<Blob \| { success: boolean, message?: string }>` | A function to handle data exporting. It receives the current `filters` and `sort` info. |
| `className`| `string` | An optional CSS class to apply to the main table container. |
| `style` | `React.CSSProperties` | Optional inline styles to apply to the main container. |
---