jattac.libs.web.responsive-table 0.3.5 → 0.3.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +662 -662
- package/dist/UI/ResponsiveTable.d.ts +1 -0
- package/dist/index.js +14 -8
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,662 +1,662 @@
|
|
|
1
|
-
# ResponsiveTable: A Modern and Flexible React Table Component
|
|
2
|
-
|
|
3
|
-
ResponsiveTable is a powerful, lightweight, and fully responsive React component for creating beautiful and functional tables. It’s designed to look great on any device, adapting from a traditional table layout on desktops to a clean, card-based view on mobile screens.
|
|
4
|
-
|
|
5
|
-
## Features
|
|
6
|
-
|
|
7
|
-
- **Mobile-First Design**: Automatically switches to a card layout on smaller screens for optimal readability.
|
|
8
|
-
- **Highly Customizable**: Tailor the look and feel of columns, headers, and footers.
|
|
9
|
-
- **Dynamic Data Handling**: Define columns and footers based on your data or application state.
|
|
10
|
-
- **Delightful Animations**: Includes an optional skeleton loader and staggered row entrance animations.
|
|
11
|
-
- **Interactive Elements**: Easily add click handlers for rows, headers, and footer cells.
|
|
12
|
-
- **Efficient & Responsive**: Built with efficiency in mind, including debounced resize handling for smooth transitions.
|
|
13
|
-
- **Easy to Use**: A simple and intuitive API for quick integration.
|
|
14
|
-
- **Extensible Plugin System**: Easily add new functionalities like filtering, sorting, or infinite scrolling.
|
|
15
|
-
|
|
16
|
-
## Installation
|
|
17
|
-
|
|
18
|
-
To get started, install the package from npm:
|
|
19
|
-
|
|
20
|
-
```bash
|
|
21
|
-
npm install jattac.libs.web.responsive-table
|
|
22
|
-
```
|
|
23
|
-
|
|
24
|
-
## Getting Started
|
|
25
|
-
|
|
26
|
-
Here’s a basic example to get you up and running in minutes.
|
|
27
|
-
|
|
28
|
-
```jsx
|
|
29
|
-
import React from 'react';
|
|
30
|
-
import ResponsiveTable from 'jattac.libs.web.responsive-table';
|
|
31
|
-
|
|
32
|
-
const GettingStarted = () => {
|
|
33
|
-
const columns = [
|
|
34
|
-
{ displayLabel: 'Name', dataKey: 'name', cellRenderer: (row) => row.name },
|
|
35
|
-
{ displayLabel: 'Age', dataKey: 'age', cellRenderer: (row) => row.age },
|
|
36
|
-
{ displayLabel: 'City', dataKey: 'city', cellRenderer: (row) => row.city },
|
|
37
|
-
];
|
|
38
|
-
|
|
39
|
-
const data = [
|
|
40
|
-
{ name: 'Alice', age: 32, city: 'New York' },
|
|
41
|
-
{ name: 'Bob', age: 28, city: 'Los Angeles' },
|
|
42
|
-
{ name: 'Charlie', age: 45, city: 'Chicago' },
|
|
43
|
-
];
|
|
44
|
-
|
|
45
|
-
return <ResponsiveTable columnDefinitions={columns} data={data} />;
|
|
46
|
-
};
|
|
47
|
-
|
|
48
|
-
export default GettingStarted;
|
|
49
|
-
```
|
|
50
|
-
|
|
51
|
-
This will render a table that automatically adapts to the screen size. On a desktop, it will look like a standard table, and on mobile, it will switch to a card-based layout.
|
|
52
|
-
|
|
53
|
-
---
|
|
54
|
-
|
|
55
|
-
## Comprehensive Examples
|
|
56
|
-
|
|
57
|
-
### Example 1: Loading State and Animations
|
|
58
|
-
|
|
59
|
-
You can provide a seamless user experience by showing a skeleton loader while your data is being fetched, and then animating the rows in when the data is ready.
|
|
60
|
-
|
|
61
|
-
```jsx
|
|
62
|
-
import React, { useState, useEffect } from 'react';
|
|
63
|
-
import ResponsiveTable from 'jattac.libs.web.responsive-table';
|
|
64
|
-
|
|
65
|
-
const AnimatedTable = () => {
|
|
66
|
-
const [data, setData] = useState([]);
|
|
67
|
-
const [isLoading, setIsLoading] = useState(true);
|
|
68
|
-
|
|
69
|
-
const columns = [
|
|
70
|
-
{ displayLabel: 'User', cellRenderer: (row) => row.name },
|
|
71
|
-
{ displayLabel: 'Email', cellRenderer: (row) => row.email },
|
|
72
|
-
];
|
|
73
|
-
|
|
74
|
-
useEffect(() => {
|
|
75
|
-
// Simulate a network request
|
|
76
|
-
setTimeout(() => {
|
|
77
|
-
setData([
|
|
78
|
-
{ name: 'Grace', email: 'grace@example.com' },
|
|
79
|
-
{ name: 'Henry', email: 'henry@example.com' },
|
|
80
|
-
]);
|
|
81
|
-
setIsLoading(false);
|
|
82
|
-
}, 2000);
|
|
83
|
-
}, []);
|
|
84
|
-
|
|
85
|
-
return (
|
|
86
|
-
<ResponsiveTable columnDefinitions={columns} data={data} animationProps={{ isLoading, animateOnLoad: true }} />
|
|
87
|
-
);
|
|
88
|
-
};
|
|
89
|
-
```
|
|
90
|
-
|
|
91
|
-
### Example 2: Adding a Clickable Row Action
|
|
92
|
-
|
|
93
|
-
You can make rows clickable to perform actions, such as navigating to a details page or opening a modal.
|
|
94
|
-
|
|
95
|
-
```jsx
|
|
96
|
-
import React from 'react';
|
|
97
|
-
import ResponsiveTable from 'jattac.libs.web.responsive-table';
|
|
98
|
-
|
|
99
|
-
const ClickableRows = () => {
|
|
100
|
-
const columns = [
|
|
101
|
-
{ displayLabel: 'Product', cellRenderer: (row) => row.product },
|
|
102
|
-
{ displayLabel: 'Price', cellRenderer: (row) => `${row.price.toFixed(2)}` },
|
|
103
|
-
];
|
|
104
|
-
|
|
105
|
-
const data = [
|
|
106
|
-
{ id: 1, product: 'Laptop', price: 1200 },
|
|
107
|
-
{ id: 2, product: 'Keyboard', price: 75 },
|
|
108
|
-
];
|
|
109
|
-
|
|
110
|
-
const handleRowClick = (item) => {
|
|
111
|
-
alert(`You clicked on product ID: ${item.id}`);
|
|
112
|
-
};
|
|
113
|
-
|
|
114
|
-
return <ResponsiveTable columnDefinitions={columns} data={data} onRowClick={handleRowClick} />;
|
|
115
|
-
};
|
|
116
|
-
```
|
|
117
|
-
|
|
118
|
-
### Example 3: Custom Cell Rendering
|
|
119
|
-
|
|
120
|
-
You can render any React component inside a cell, allowing for rich content like buttons, links, or status badges.
|
|
121
|
-
|
|
122
|
-
```jsx
|
|
123
|
-
import React from 'react';
|
|
124
|
-
import ResponsiveTable from 'jattac.libs.web.responsive-table';
|
|
125
|
-
|
|
126
|
-
const CustomCells = () => {
|
|
127
|
-
const columns = [
|
|
128
|
-
{ displayLabel: <strong>User</strong>, cellRenderer: (row) => <strong>{row.user}</strong> },
|
|
129
|
-
{
|
|
130
|
-
displayLabel: 'Status',
|
|
131
|
-
cellRenderer: (row) => (
|
|
132
|
-
<span
|
|
133
|
-
style={{
|
|
134
|
-
color: row.status === 'Active' ? 'green' : 'red',
|
|
135
|
-
fontWeight: 'bold',
|
|
136
|
-
}}
|
|
137
|
-
>
|
|
138
|
-
{row.status}
|
|
139
|
-
</span>
|
|
140
|
-
),
|
|
141
|
-
},
|
|
142
|
-
{
|
|
143
|
-
displayLabel: 'Action',
|
|
144
|
-
cellRenderer: (row) => <button onClick={() => alert(`Editing ${row.user}`)}>Edit</button>,
|
|
145
|
-
},
|
|
146
|
-
];
|
|
147
|
-
|
|
148
|
-
const data = [
|
|
149
|
-
{ user: 'Eve', status: 'Active' },
|
|
150
|
-
{ user: 'Frank', status: 'Inactive' },
|
|
151
|
-
];
|
|
152
|
-
|
|
153
|
-
return <ResponsiveTable columnDefinitions={columns} data={data} />;
|
|
154
|
-
};
|
|
155
|
-
```
|
|
156
|
-
|
|
157
|
-
### Example 4: Dynamic and Conditional Columns
|
|
158
|
-
|
|
159
|
-
Columns can be generated dynamically based on your data or application state. This is useful for creating flexible tables that adapt to different datasets.
|
|
160
|
-
|
|
161
|
-
```jsx
|
|
162
|
-
import React from 'react';
|
|
163
|
-
import ResponsiveTable from 'jattac.libs.web.responsive-table';
|
|
164
|
-
|
|
165
|
-
const DynamicColumns = ({ isAdmin }) => {
|
|
166
|
-
// Base columns for all users
|
|
167
|
-
const columns = [
|
|
168
|
-
{ displayLabel: 'File Name', cellRenderer: (row) => row.fileName },
|
|
169
|
-
{ displayLabel: 'Size', cellRenderer: (row) => `${row.size} KB` },
|
|
170
|
-
];
|
|
171
|
-
|
|
172
|
-
// Add an admin-only column conditionally
|
|
173
|
-
if (isAdmin) {
|
|
174
|
-
columns.push({
|
|
175
|
-
displayLabel: 'Admin Actions',
|
|
176
|
-
cellRenderer: (row) => <button onClick={() => alert(`Deleting ${row.fileName}`)}>Delete</button>,
|
|
177
|
-
});
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
const data = [
|
|
181
|
-
{ fileName: 'document.pdf', size: 1024 },
|
|
182
|
-
{ fileName: 'image.jpg', size: 512 },
|
|
183
|
-
];
|
|
184
|
-
|
|
185
|
-
return <ResponsiveTable columnDefinitions={columns} data={data} />;
|
|
186
|
-
};
|
|
187
|
-
```
|
|
188
|
-
|
|
189
|
-
### Example 5: Advanced Footer with Labels and Interactivity
|
|
190
|
-
|
|
191
|
-
You can add a footer to display summary information, such as totals or averages. The footer is also responsive and will appear correctly in both desktop and mobile views. With the enhanced footer functionality, you can provide explicit labels for mobile view and add click handlers to footer cells.
|
|
192
|
-
|
|
193
|
-
```jsx
|
|
194
|
-
import React from 'react';
|
|
195
|
-
import ResponsiveTable from 'jattac.libs.web.responsive-table';
|
|
196
|
-
|
|
197
|
-
const TableWithFooter = () => {
|
|
198
|
-
const columns = [
|
|
199
|
-
{ displayLabel: 'Item', cellRenderer: (row) => row.item },
|
|
200
|
-
{ displayLabel: 'Quantity', cellRenderer: (row) => row.quantity },
|
|
201
|
-
{ displayLabel: 'Price', cellRenderer: (row) => `${row.price.toFixed(2)}` },
|
|
202
|
-
];
|
|
203
|
-
|
|
204
|
-
const data = [
|
|
205
|
-
{ item: 'Apples', quantity: 10, price: 1.5 },
|
|
206
|
-
{ item: 'Oranges', quantity: 5, price: 2.0 },
|
|
207
|
-
{ item: 'Bananas', quantity: 15, price: 0.5 },
|
|
208
|
-
];
|
|
209
|
-
|
|
210
|
-
const total = data.reduce((sum, row) => sum + row.quantity * row.price, 0);
|
|
211
|
-
|
|
212
|
-
const footerRows = [
|
|
213
|
-
{
|
|
214
|
-
columns: [
|
|
215
|
-
{
|
|
216
|
-
colSpan: 2,
|
|
217
|
-
cellRenderer: () => <strong>Total:</strong>,
|
|
218
|
-
},
|
|
219
|
-
{
|
|
220
|
-
colSpan: 1,
|
|
221
|
-
displayLabel: 'Total',
|
|
222
|
-
cellRenderer: () => <strong>${total.toFixed(2)}</strong>,
|
|
223
|
-
onCellClick: () => alert('Total clicked!'),
|
|
224
|
-
},
|
|
225
|
-
],
|
|
226
|
-
},
|
|
227
|
-
];
|
|
228
|
-
|
|
229
|
-
return <ResponsiveTable columnDefinitions={columns} data={data} footerRows={footerRows} />;
|
|
230
|
-
};
|
|
231
|
-
```
|
|
232
|
-
|
|
233
|
-
### Example 6: Disabling Page-Level Sticky Header
|
|
234
|
-
|
|
235
|
-
By default, the table header remains fixed to the top of the viewport as the user scrolls down the page. This ensures the column titles are always visible. To disable this behavior and have the header scroll away with the rest of the page, set the `enablePageLevelStickyHeader` prop to `false`.
|
|
236
|
-
|
|
237
|
-
```jsx
|
|
238
|
-
import React from 'react';
|
|
239
|
-
import ResponsiveTable from 'jattac.libs.web.responsive-table';
|
|
240
|
-
|
|
241
|
-
const NonStickyHeaderTable = () => {
|
|
242
|
-
// We need enough data to make the page scroll
|
|
243
|
-
const data = Array.from({ length: 50 }, (_, i) => ({
|
|
244
|
-
id: i + 1,
|
|
245
|
-
item: `Item #${i + 1}`,
|
|
246
|
-
description: 'This is a sample item.',
|
|
247
|
-
}));
|
|
248
|
-
|
|
249
|
-
const columns = [
|
|
250
|
-
{ displayLabel: 'ID', cellRenderer: (row) => row.id },
|
|
251
|
-
{ displayLabel: 'Item', cellRenderer: (row) => row.item },
|
|
252
|
-
{ displayLabel: 'Description', cellRenderer: (row) => row.description },
|
|
253
|
-
];
|
|
254
|
-
|
|
255
|
-
return (
|
|
256
|
-
<div>
|
|
257
|
-
<h1 style={{ height: '50vh', display: 'flex', alignItems: 'center' }}>Scroll down to see the table</h1>
|
|
258
|
-
<ResponsiveTable
|
|
259
|
-
columnDefinitions={columns}
|
|
260
|
-
data={data}
|
|
261
|
-
enablePageLevelStickyHeader={false} // <-- Here's the magic switch!
|
|
262
|
-
/>
|
|
263
|
-
<div style={{ height: '50vh' }} />
|
|
264
|
-
</div>
|
|
265
|
-
);
|
|
266
|
-
};
|
|
267
|
-
```
|
|
268
|
-
|
|
269
|
-
---
|
|
270
|
-
|
|
271
|
-
## Plugin System
|
|
272
|
-
|
|
273
|
-
ResponsiveTable is designed with an extensible plugin system, allowing developers to easily add new functionalities or modify existing behaviors without altering the core component. Plugins can interact with the table's data, render custom UI elements (like headers or footers), and respond to table events.
|
|
274
|
-
|
|
275
|
-
### Plugin Execution Order
|
|
276
|
-
|
|
277
|
-
> **Note:** Plugins process data sequentially in the order they are provided in the `plugins` array. This can have important performance and behavioral implications.
|
|
278
|
-
|
|
279
|
-
For example, consider the `SortPlugin` and `FilterPlugin`.
|
|
280
|
-
|
|
281
|
-
- `plugins={[new SortPlugin(), new FilterPlugin()]}`: This will **sort** the entire dataset first, and then **filter** the sorted data.
|
|
282
|
-
- `plugins={[new FilterPlugin(), new SortPlugin()]}`: This will **filter** the dataset first, and then **sort** the much smaller, filtered result.
|
|
283
|
-
|
|
284
|
-
For the best performance, it is highly recommended to **filter first, then sort**.
|
|
285
|
-
|
|
286
|
-
### How to Use Plugins
|
|
287
|
-
|
|
288
|
-
Plugins are passed to the `ResponsiveTable` component via the `plugins` prop, which accepts an array of `IResponsiveTablePlugin` instances. Some common functionalities, like filtering and infinite scrolling, are provided as built-in plugins that can be enabled via specific props (`filterProps` and `infiniteScrollProps`). When these props are used, the corresponding built-in plugins are automatically initialized if not already provided in the `plugins` array.
|
|
289
|
-
|
|
290
|
-
```jsx
|
|
291
|
-
import React from 'react';
|
|
292
|
-
// Note: All plugins are exported from the main package entry point.
|
|
293
|
-
import ResponsiveTable, { FilterPlugin } from 'jattac.libs.web.responsive-table';
|
|
294
|
-
|
|
295
|
-
const MyTableWithPlugins = () => {
|
|
296
|
-
const columns = [
|
|
297
|
-
{ displayLabel: 'Name', dataKey: 'name', cellRenderer: (row) => row.name, getFilterableValue: (row) => row.name },
|
|
298
|
-
{
|
|
299
|
-
displayLabel: 'Age',
|
|
300
|
-
dataKey: 'age',
|
|
301
|
-
cellRenderer: (row) => row.age,
|
|
302
|
-
getFilterableValue: (row) => row.age.toString(),
|
|
303
|
-
},
|
|
304
|
-
];
|
|
305
|
-
|
|
306
|
-
const data = [
|
|
307
|
-
{ name: 'Alice', age: 32 },
|
|
308
|
-
{ name: 'Bob', age: 28 },
|
|
309
|
-
{ name: 'Charlie', age: 45 },
|
|
310
|
-
];
|
|
311
|
-
|
|
312
|
-
return (
|
|
313
|
-
<ResponsiveTable
|
|
314
|
-
columnDefinitions={columns}
|
|
315
|
-
data={data}
|
|
316
|
-
// Enable built-in filter plugin via props
|
|
317
|
-
filterProps={{ showFilter: true, filterPlaceholder: 'Search by name or age...' }}
|
|
318
|
-
// Or provide a custom instance of the plugin
|
|
319
|
-
// plugins={[new FilterPlugin()]}
|
|
320
|
-
/>
|
|
321
|
-
);
|
|
322
|
-
};
|
|
323
|
-
```
|
|
324
|
-
|
|
325
|
-
### Built-in Plugins
|
|
326
|
-
|
|
327
|
-
#### `SortPlugin`
|
|
328
|
-
|
|
329
|
-
The `SortPlugin` provides powerful, type-safe, and highly customizable column sorting. It adds intuitive UI cues, allowing users to click column headers to sort the data in ascending, descending, or original order.
|
|
330
|
-
|
|
331
|
-
**Enabling the `SortPlugin`:**
|
|
332
|
-
|
|
333
|
-
To use the plugin, you must first import it and provide a generic instance of it to the `plugins` prop. The real power comes from making the plugin instance generic with your data type, which provides type-safety and IDE autocompletion for the sort comparer helpers.
|
|
334
|
-
|
|
335
|
-
```jsx
|
|
336
|
-
import React from 'react';
|
|
337
|
-
import ResponsiveTable, { IResponsiveTableColumnDefinition, SortPlugin } from 'jattac.libs.web.responsive-table';
|
|
338
|
-
|
|
339
|
-
// Define the shape of your data
|
|
340
|
-
interface User {
|
|
341
|
-
id: number;
|
|
342
|
-
name: string;
|
|
343
|
-
signupDate: string;
|
|
344
|
-
logins: number;
|
|
345
|
-
}
|
|
346
|
-
|
|
347
|
-
// 1. Create a single, generic instance of the plugin.
|
|
348
|
-
const sortPlugin = new SortPlugin<User>({
|
|
349
|
-
initialSortColumn: 'user_logins', // Use the columnId
|
|
350
|
-
initialSortDirection: 'desc',
|
|
351
|
-
});
|
|
352
|
-
|
|
353
|
-
// 2. Define the columns, using the helpers directly from the plugin instance.
|
|
354
|
-
const columnDefinitions: IResponsiveTableColumnDefinition<User>[] = [
|
|
355
|
-
// ... see examples below
|
|
356
|
-
];
|
|
357
|
-
|
|
358
|
-
const UserTable = ({ users }) => (
|
|
359
|
-
<ResponsiveTable
|
|
360
|
-
columnDefinitions={columnDefinitions}
|
|
361
|
-
data={users}
|
|
362
|
-
// 3. Pass the already-configured plugin to the table.
|
|
363
|
-
plugins={[sortPlugin]}
|
|
364
|
-
/>
|
|
365
|
-
);
|
|
366
|
-
```
|
|
367
|
-
|
|
368
|
-
**How to Make Columns Sortable (Opt-In):**
|
|
369
|
-
|
|
370
|
-
A column is made sortable by adding a **`columnId`** and either a `sortComparer` or a `getSortableValue` property to its definition. The `columnId` must be a unique string that identifies the column.
|
|
371
|
-
|
|
372
|
-
- `sortComparer`: A function that defines the exact comparison logic. This is the most powerful option and should be used for complex data types or custom logic.
|
|
373
|
-
- `getSortableValue`: A simpler function that just returns the primitive value (string, number, etc.) to be used in a default comparison.
|
|
374
|
-
|
|
375
|
-
**Example 1: Using Type-Safe Comparer Helpers**
|
|
376
|
-
|
|
377
|
-
The `SortPlugin` instance provides a `comparers` object with pre-built, type-safe helper functions to eliminate boilerplate for common sorting scenarios. This is the recommended approach.
|
|
378
|
-
|
|
379
|
-
```jsx
|
|
380
|
-
const columnDefinitions: IResponsiveTableColumnDefinition<User>[] = [
|
|
381
|
-
{
|
|
382
|
-
columnId: 'user_name',
|
|
383
|
-
displayLabel: 'Name',
|
|
384
|
-
dataKey: 'name',
|
|
385
|
-
cellRenderer: (user) => user.name,
|
|
386
|
-
// The plugin instance itself provides the type-safe helpers.
|
|
387
|
-
// The string 'name' is fully type-checked against the User interface.
|
|
388
|
-
sortComparer: sortPlugin.comparers.caseInsensitiveString('name'),
|
|
389
|
-
},
|
|
390
|
-
{
|
|
391
|
-
columnId: 'user_signup_date',
|
|
392
|
-
displayLabel: 'Signup Date',
|
|
393
|
-
dataKey: 'signupDate',
|
|
394
|
-
cellRenderer: (user) => new Date(user.signupDate).toLocaleDateString(),
|
|
395
|
-
// IDE autocompletion for 'signupDate' works perfectly.
|
|
396
|
-
sortComparer: sortPlugin.comparers.date('signupDate'),
|
|
397
|
-
},
|
|
398
|
-
{
|
|
399
|
-
columnId: 'user_logins',
|
|
400
|
-
displayLabel: 'Logins',
|
|
401
|
-
dataKey: 'logins',
|
|
402
|
-
cellRenderer: (user) => user.logins,
|
|
403
|
-
sortComparer: sortPlugin.comparers.numeric('logins'),
|
|
404
|
-
},
|
|
405
|
-
{
|
|
406
|
-
columnId: 'user_actions',
|
|
407
|
-
displayLabel: 'Actions',
|
|
408
|
-
// This column is NOT sortable because it has no sort-related properties.
|
|
409
|
-
cellRenderer: (user) => <button>View</button>,
|
|
410
|
-
},
|
|
411
|
-
];
|
|
412
|
-
```
|
|
413
|
-
|
|
414
|
-
**Example 2: Writing a Custom `sortComparer` for a Computed Column**
|
|
415
|
-
|
|
416
|
-
> **Important:** When writing a custom `sortComparer`, you **must** include all three parameters (`a`, `b`, and `direction`) in your function signature. Forgetting the `direction` parameter will cause descending sorts to fail. The IDE is configured to provide a warning if you forget, and the developer console will also show a warning at runtime.
|
|
417
|
-
|
|
418
|
-
For unique requirements, you can write your own comparison function. Notice how `columnId` is used without a `dataKey`.
|
|
419
|
-
|
|
420
|
-
```jsx
|
|
421
|
-
const columnDefinitions: IResponsiveTableColumnDefinition<User>[] = [
|
|
422
|
-
{
|
|
423
|
-
columnId: 'user_name_custom',
|
|
424
|
-
displayLabel: 'Name',
|
|
425
|
-
cellRenderer: (user) => user.name,
|
|
426
|
-
// Writing custom logic for a case-sensitive sort
|
|
427
|
-
sortComparer: (a, b, direction) => {
|
|
428
|
-
const nameA = a.name; // No .toLowerCase()
|
|
429
|
-
const nameB = b.name;
|
|
430
|
-
if (nameA < nameB) return direction === 'asc' ? -1 : 1;
|
|
431
|
-
if (nameA > nameB) return direction === 'asc' ? 1 : -1;
|
|
432
|
-
return 0;
|
|
433
|
-
},
|
|
434
|
-
},
|
|
435
|
-
];
|
|
436
|
-
```
|
|
437
|
-
|
|
438
|
-
**Example 3: Using `getSortableValue` for Simple Cases**
|
|
439
|
-
|
|
440
|
-
If you don't need special logic, `getSortableValue` is a concise way to enable default sorting on a property.
|
|
441
|
-
|
|
442
|
-
```jsx
|
|
443
|
-
const columnDefinitions: IResponsiveTableColumnDefinition<User>[] = [
|
|
444
|
-
{
|
|
445
|
-
columnId: 'user_logins_simple',
|
|
446
|
-
displayLabel: 'Logins',
|
|
447
|
-
dataKey: 'logins',
|
|
448
|
-
cellRenderer: (user) => user.logins,
|
|
449
|
-
// This enables a simple, default numerical sort on the 'logins' property.
|
|
450
|
-
getSortableValue: (user) => user.logins,
|
|
451
|
-
},
|
|
452
|
-
];
|
|
453
|
-
```
|
|
454
|
-
|
|
455
|
-
**Plugin Options (via `new SortPlugin(options)`):**
|
|
456
|
-
|
|
457
|
-
| Prop | Type | Description |
|
|
458
|
-
| ---------------------- | ----------------- | ---------------------------------------------------- |
|
|
459
|
-
| `initialSortColumn` | `string` | The `columnId` of the column to sort by initially. |
|
|
460
|
-
| `initialSortDirection` | `'asc' \| 'desc'` | The direction for the initial sort. |
|
|
461
|
-
|
|
462
|
-
**`SortPlugin.comparers` API:**
|
|
463
|
-
|
|
464
|
-
The `comparers` object on your `SortPlugin` instance provides the following helper methods. Each method is a factory that takes a `dataKey` (which is type-checked against your data model) and returns a `sortComparer` function.
|
|
465
|
-
|
|
466
|
-
| Method | Description |
|
|
467
|
-
| -------------------------------- | ----------------------------------------------------------------------------- |
|
|
468
|
-
| `numeric(dataKey)` | Performs a standard numerical sort. |
|
|
469
|
-
| `caseInsensitiveString(dataKey)` | Performs a case-insensitive alphabetical sort. |
|
|
470
|
-
| `date(dataKey)` | Correctly sorts dates, assuming the data is a valid date string or timestamp. |
|
|
471
|
-
|
|
472
|
-
#### `FilterPlugin`
|
|
473
|
-
|
|
474
|
-
> **Warning: Incompatible with Infinite Scroll**
|
|
475
|
-
> The `FilterPlugin` is a client-side utility that only operates on data currently loaded in the browser. It is **not compatible** with the `InfiniteScrollPlugin`, as it cannot search data that has not yet been fetched from the server. For tables using infinite scroll, filtering logic must be implemented server-side by your application and passed into the `onLoadMore` function.
|
|
476
|
-
|
|
477
|
-
Provides a search input to filter table data. It can be enabled by setting `filterProps.showFilter` to `true` on the `ResponsiveTable` component. For columns to be filterable, you must provide a `getFilterableValue` function in their `IResponsiveTableColumnDefinition`.
|
|
478
|
-
|
|
479
|
-
**Props for `FilterPlugin` (via `filterProps` on `ResponsiveTable`):**
|
|
480
|
-
|
|
481
|
-
| Prop | Type | Description |
|
|
482
|
-
| ------------------- | --------- | --------------------------------------------------------------- |
|
|
483
|
-
| `showFilter` | `boolean` | If `true`, displays a filter input field above the table. |
|
|
484
|
-
| `filterPlaceholder` | `string` | Placeholder text for the filter input. Defaults to "Search...". |
|
|
485
|
-
|
|
486
|
-
**Example with `FilterPlugin`:**
|
|
487
|
-
|
|
488
|
-
```jsx
|
|
489
|
-
import React from 'react';
|
|
490
|
-
import ResponsiveTable from 'jattac.libs.web.responsive-table';
|
|
491
|
-
|
|
492
|
-
const FilterableTable = () => {
|
|
493
|
-
const initialData = [
|
|
494
|
-
{ id: 1, name: 'Alice', email: 'alice@example.com' },
|
|
495
|
-
{ id: 2, name: 'Bob', email: 'bob@example.com' },
|
|
496
|
-
{ id: 3, name: 'Charlie', email: 'charlie@example.com' },
|
|
497
|
-
{ id: 4, name: 'David', email: 'david@example.com' },
|
|
498
|
-
];
|
|
499
|
-
|
|
500
|
-
const columns = [
|
|
501
|
-
{ displayLabel: 'ID', cellRenderer: (row) => row.id, getFilterableValue: (row) => row.id.toString() },
|
|
502
|
-
{ displayLabel: 'Name', cellRenderer: (row) => row.name, getFilterableValue: (row) => row.name },
|
|
503
|
-
{ displayLabel: 'Email', cellRenderer: (row) => row.email, getFilterableValue: (row) => row.email },
|
|
504
|
-
];
|
|
505
|
-
|
|
506
|
-
return (
|
|
507
|
-
<ResponsiveTable
|
|
508
|
-
columnDefinitions={columns}
|
|
509
|
-
data={initialData}
|
|
510
|
-
filterProps={{ showFilter: true, filterPlaceholder: 'Filter users...' }}
|
|
511
|
-
/>
|
|
512
|
-
);
|
|
513
|
-
};
|
|
514
|
-
```
|
|
515
|
-
|
|
516
|
-
#### Infinite Scroll
|
|
517
|
-
|
|
518
|
-
> **Warning: Incompatible with Client-Side Filtering**
|
|
519
|
-
> The infinite scroll feature fetches data in chunks from a server. It is **not compatible** with the client-side `FilterPlugin`. For filtering to work correctly with infinite scroll, you must implement the filtering logic on your server and have the `onLoadMore` function fetch data that is already filtered.
|
|
520
|
-
|
|
521
|
-
Enables a simple infinite scroll for loading more data as the user scrolls to the bottom of the table. This is useful for progressively loading data from an API without needing traditional pagination buttons. When enabled, the `ResponsiveTable` renders a specialized internal component optimized for this purpose.
|
|
522
|
-
|
|
523
|
-
> **Important:** To enable infinite scroll, you **must** give the table a bounded height. This is done by passing the `maxHeight` prop to the `<ResponsiveTable>`. This prop creates a scrollable container for the table body, which is required for the scroll detection to work.
|
|
524
|
-
|
|
525
|
-
> **Performance Note:** This implementation renders all loaded rows into the DOM to guarantee correct column alignment and simplicity. It is **not a virtualized list**. For extremely large datasets (many thousands of rows), performance may degrade as more rows are loaded. It is best suited for scenarios where loading a few hundred up to a couple thousand rows is expected.
|
|
526
|
-
|
|
527
|
-
**Configuration (via `infiniteScrollProps` on `ResponsiveTable`):**
|
|
528
|
-
|
|
529
|
-
| Prop | Type | Description |
|
|
530
|
-
| ---------------------- | ---------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
531
|
-
| `enableInfiniteScroll` | `boolean` | If `true`, enables infinite scrolling. |
|
|
532
|
-
| `hasMore` | `boolean` | **Optional.** Controls the loading indicator. If omitted, the component infers this state automatically by checking if `onLoadMore` returns an empty array or `null`. If provided, your app is responsible for managing this state. |
|
|
533
|
-
| `onLoadMore` | `(currentData: TData[]) => Promise<TData[] | null>` | A callback function that fires when the user scrolls near the end. It should fetch the next page of data and return it in a Promise. The component will stop trying to load more when this function returns `null` or an empty array. |
|
|
534
|
-
| `loadingMoreComponent` | `ReactNode` | A custom component to display at the bottom while new data is being loaded. Defaults to a spinner animation. |
|
|
535
|
-
| `noMoreDataComponent` | `ReactNode` | A custom component to display at the bottom when `hasMore` is `false`. Defaults to a "No more data" message. |
|
|
536
|
-
|
|
537
|
-
**Comprehensive Example:**
|
|
538
|
-
|
|
539
|
-
Here is a complete example showing how to use the infinite scroll feature. The parent component only needs to provide a function that fetches the next page of data.
|
|
540
|
-
|
|
541
|
-
```jsx
|
|
542
|
-
import React, { useState, useCallback } from 'react';
|
|
543
|
-
import ResponsiveTable from 'jattac.libs.web.responsive-table';
|
|
544
|
-
|
|
545
|
-
// Define the shape of our data items
|
|
546
|
-
interface DataItem {
|
|
547
|
-
id: number;
|
|
548
|
-
value: string;
|
|
549
|
-
}
|
|
550
|
-
|
|
551
|
-
// This is a mock API function to simulate fetching data.
|
|
552
|
-
// In a real app, this would be an actual network request.
|
|
553
|
-
const fetchData = async (page: number): Promise<DataItem[]> => {
|
|
554
|
-
console.log(`Fetching page: ${page}`);
|
|
555
|
-
return new Promise((resolve) => {
|
|
556
|
-
setTimeout(() => {
|
|
557
|
-
// Return an empty array for pages > 5 to simulate the end of the data
|
|
558
|
-
if (page > 5) {
|
|
559
|
-
resolve([]);
|
|
560
|
-
return;
|
|
561
|
-
}
|
|
562
|
-
// Generate 20 new items for the current page
|
|
563
|
-
const newData = Array.from({ length: 20 }, (_, i) => ({
|
|
564
|
-
id: page * 20 + i,
|
|
565
|
-
value: `Item #${page * 20 + i}`,
|
|
566
|
-
}));
|
|
567
|
-
resolve(newData);
|
|
568
|
-
}, 500); // Simulate network latency
|
|
569
|
-
});
|
|
570
|
-
};
|
|
571
|
-
|
|
572
|
-
const InfiniteScrollExample = () => {
|
|
573
|
-
// Keep track of the next page to fetch.
|
|
574
|
-
const [nextPage, setNextPage] = useState(0);
|
|
575
|
-
|
|
576
|
-
// The onLoadMore function is now much simpler.
|
|
577
|
-
// It just needs to fetch the data and return it.
|
|
578
|
-
// The table will handle appending the data and managing the `hasMore` state internally.
|
|
579
|
-
const loadMoreItems = useCallback(async () => {
|
|
580
|
-
const newItems = await fetchData(nextPage);
|
|
581
|
-
setNextPage((prevPage) => prevPage + 1);
|
|
582
|
-
return newItems; // <-- Simply return the new items
|
|
583
|
-
}, [nextPage]);
|
|
584
|
-
|
|
585
|
-
const columns = [
|
|
586
|
-
{ displayLabel: 'ID', dataKey: 'id', cellRenderer: (row) => row.id },
|
|
587
|
-
{ displayLabel: 'Value', dataKey: 'value', cellRenderer: (row) => row.value },
|
|
588
|
-
];
|
|
589
|
-
|
|
590
|
-
return (
|
|
591
|
-
// The table MUST be inside a container with a defined height.
|
|
592
|
-
<div style={{ height: '400px' }}>
|
|
593
|
-
<ResponsiveTable
|
|
594
|
-
columnDefinitions={columns}
|
|
595
|
-
data={[]} // Start with an empty array of initial data
|
|
596
|
-
maxHeight="100%"
|
|
597
|
-
infiniteScrollProps={{
|
|
598
|
-
enableInfiniteScroll: true,
|
|
599
|
-
onLoadMore: loadMoreItems,
|
|
600
|
-
|
|
601
|
-
loadingMoreComponent: <h4>Loading more items...</h4>,
|
|
602
|
-
noMoreDataComponent: <p>You've reached the end!</p>,
|
|
603
|
-
}}
|
|
604
|
-
/>
|
|
605
|
-
</div>
|
|
606
|
-
);
|
|
607
|
-
};
|
|
608
|
-
```
|
|
609
|
-
|
|
610
|
-
---
|
|
611
|
-
|
|
612
|
-
## API Reference
|
|
613
|
-
|
|
614
|
-
### `ResponsiveTable` Props
|
|
615
|
-
|
|
616
|
-
| Prop | Type | Required | Description |
|
|
617
|
-
| ----------------------------- | ------------------------------------ | -------- | --------------------------------------------------------------------------------------------------- |
|
|
618
|
-
| `columnDefinitions` | `IResponsiveTableColumnDefinition[]` | Yes | An array of objects defining the table columns. Can also accept a function for dynamic column generation. |
|
|
619
|
-
| `data` | `TData[]` | Yes | An array of data objects to populate the table rows. |
|
|
620
|
-
| `footerRows` | `IFooterRowDefinition[]` | No | An array of objects defining the table footer. |
|
|
621
|
-
| `onRowClick` | `(item: TData) => void` | No | A callback function that is triggered when a row is clicked. |
|
|
622
|
-
| `noDataComponent` | `ReactNode` | No | A custom component to display when there is no data. |
|
|
623
|
-
| `maxHeight` | `string` | No | Sets a maximum height for the table body, making it scrollable. |
|
|
624
|
-
| `mobileBreakpoint` | `number` | No | The pixel width at which the table switches to the mobile view. Defaults to `600`. |
|
|
625
|
-
| `enablePageLevelStickyHeader` | `boolean` | No | If `false`, disables the header from sticking to the top of the page on scroll. Defaults to `true`. |
|
|
626
|
-
| `plugins` | `IResponsiveTablePlugin<TData>[]` | No | An array of plugin instances to extend table functionality. |
|
|
627
|
-
| `infiniteScrollProps` | `object` | No | Configuration for the infinite scroll feature. When enabled, a specialized component handles data loading. |
|
|
628
|
-
| `filterProps` | `object` | No | Configuration for the built-in filter plugin. |
|
|
629
|
-
| `animationProps` | `object` | No | Configuration for animations, including `isLoading` and `animateOnLoad`. |
|
|
630
|
-
|
|
631
|
-
### `IResponsiveTableColumnDefinition<TData>`
|
|
632
|
-
|
|
633
|
-
| Property | Type | Required | Description |
|
|
634
|
-
| -------------------- | ------------------------------------------------------------ | -------- | ---------------------------------------------------------------------------------------- |
|
|
635
|
-
| `displayLabel` | `ReactNode` | Yes | The label displayed in the table header (can be a string or any React component). |
|
|
636
|
-
| `cellRenderer` | `(row: TData) => ReactNode` | Yes | A function that returns the content to be rendered in the cell. |
|
|
637
|
-
| `columnId` | `string` | No | A unique string to identify the column. **Required** if the column is sortable. |
|
|
638
|
-
| `dataKey` | `keyof TData` | No | A key to match the column to a property in the data object. |
|
|
639
|
-
| `interactivity` | `object` | No | An object to define header interactivity (`onHeaderClick`, `id`, `className`). |
|
|
640
|
-
| `getFilterableValue` | `(row: TData) => string \| number` | No | A function that returns the string or number value to be used for filtering this column. |
|
|
641
|
-
| `getSortableValue` | `(row: TData) => any` | No | A function that returns a primitive value from a row to be used for default sorting. |
|
|
642
|
-
| `sortComparer` | `(a: TData, b: TData, direction: 'asc' \| 'desc') => number` | No | A function that provides the precise comparison logic for sorting a column. |
|
|
643
|
-
|
|
644
|
-
### `IFooterRowDefinition`
|
|
645
|
-
|
|
646
|
-
| Property | Type | Required | Description |
|
|
647
|
-
| --------- | --------------------------- | -------- | -------------------------------------------------- |
|
|
648
|
-
| `columns` | `IFooterColumnDefinition[]` | Yes | An array of column definitions for the footer row. |
|
|
649
|
-
|
|
650
|
-
### `IFooterColumnDefinition`
|
|
651
|
-
|
|
652
|
-
| Property | Type | Required | Description |
|
|
653
|
-
| -------------- | ----------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
654
|
-
| `colSpan` | `number` | Yes | The number of columns the footer cell should span. |
|
|
655
|
-
| `cellRenderer` | `() => ReactNode` | Yes | A function that returns the content for the footer cell. |
|
|
656
|
-
| `displayLabel` | `ReactNode` | No | An optional, explicit label for the footer cell. In mobile view, if `colSpan` is 1 and this is not provided, the corresponding column header will be used as a fallback. This is required for `colSpan` > 1 if you want a label to be displayed. |
|
|
657
|
-
| `onCellClick` | `() => void` | No | An optional click handler for the footer cell. |
|
|
658
|
-
| `className` | `string` | No | Optional class name for custom styling of the footer cell. |
|
|
659
|
-
|
|
660
|
-
## License
|
|
661
|
-
|
|
662
|
-
This project is licensed under the MIT License.
|
|
1
|
+
# ResponsiveTable: A Modern and Flexible React Table Component
|
|
2
|
+
|
|
3
|
+
ResponsiveTable is a powerful, lightweight, and fully responsive React component for creating beautiful and functional tables. It’s designed to look great on any device, adapting from a traditional table layout on desktops to a clean, card-based view on mobile screens.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- **Mobile-First Design**: Automatically switches to a card layout on smaller screens for optimal readability.
|
|
8
|
+
- **Highly Customizable**: Tailor the look and feel of columns, headers, and footers.
|
|
9
|
+
- **Dynamic Data Handling**: Define columns and footers based on your data or application state.
|
|
10
|
+
- **Delightful Animations**: Includes an optional skeleton loader and staggered row entrance animations.
|
|
11
|
+
- **Interactive Elements**: Easily add click handlers for rows, headers, and footer cells.
|
|
12
|
+
- **Efficient & Responsive**: Built with efficiency in mind, including debounced resize handling for smooth transitions.
|
|
13
|
+
- **Easy to Use**: A simple and intuitive API for quick integration.
|
|
14
|
+
- **Extensible Plugin System**: Easily add new functionalities like filtering, sorting, or infinite scrolling.
|
|
15
|
+
|
|
16
|
+
## Installation
|
|
17
|
+
|
|
18
|
+
To get started, install the package from npm:
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
npm install jattac.libs.web.responsive-table
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Getting Started
|
|
25
|
+
|
|
26
|
+
Here’s a basic example to get you up and running in minutes.
|
|
27
|
+
|
|
28
|
+
```jsx
|
|
29
|
+
import React from 'react';
|
|
30
|
+
import ResponsiveTable from 'jattac.libs.web.responsive-table';
|
|
31
|
+
|
|
32
|
+
const GettingStarted = () => {
|
|
33
|
+
const columns = [
|
|
34
|
+
{ displayLabel: 'Name', dataKey: 'name', cellRenderer: (row) => row.name },
|
|
35
|
+
{ displayLabel: 'Age', dataKey: 'age', cellRenderer: (row) => row.age },
|
|
36
|
+
{ displayLabel: 'City', dataKey: 'city', cellRenderer: (row) => row.city },
|
|
37
|
+
];
|
|
38
|
+
|
|
39
|
+
const data = [
|
|
40
|
+
{ name: 'Alice', age: 32, city: 'New York' },
|
|
41
|
+
{ name: 'Bob', age: 28, city: 'Los Angeles' },
|
|
42
|
+
{ name: 'Charlie', age: 45, city: 'Chicago' },
|
|
43
|
+
];
|
|
44
|
+
|
|
45
|
+
return <ResponsiveTable columnDefinitions={columns} data={data} />;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
export default GettingStarted;
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
This will render a table that automatically adapts to the screen size. On a desktop, it will look like a standard table, and on mobile, it will switch to a card-based layout.
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
## Comprehensive Examples
|
|
56
|
+
|
|
57
|
+
### Example 1: Loading State and Animations
|
|
58
|
+
|
|
59
|
+
You can provide a seamless user experience by showing a skeleton loader while your data is being fetched, and then animating the rows in when the data is ready.
|
|
60
|
+
|
|
61
|
+
```jsx
|
|
62
|
+
import React, { useState, useEffect } from 'react';
|
|
63
|
+
import ResponsiveTable from 'jattac.libs.web.responsive-table';
|
|
64
|
+
|
|
65
|
+
const AnimatedTable = () => {
|
|
66
|
+
const [data, setData] = useState([]);
|
|
67
|
+
const [isLoading, setIsLoading] = useState(true);
|
|
68
|
+
|
|
69
|
+
const columns = [
|
|
70
|
+
{ displayLabel: 'User', cellRenderer: (row) => row.name },
|
|
71
|
+
{ displayLabel: 'Email', cellRenderer: (row) => row.email },
|
|
72
|
+
];
|
|
73
|
+
|
|
74
|
+
useEffect(() => {
|
|
75
|
+
// Simulate a network request
|
|
76
|
+
setTimeout(() => {
|
|
77
|
+
setData([
|
|
78
|
+
{ name: 'Grace', email: 'grace@example.com' },
|
|
79
|
+
{ name: 'Henry', email: 'henry@example.com' },
|
|
80
|
+
]);
|
|
81
|
+
setIsLoading(false);
|
|
82
|
+
}, 2000);
|
|
83
|
+
}, []);
|
|
84
|
+
|
|
85
|
+
return (
|
|
86
|
+
<ResponsiveTable columnDefinitions={columns} data={data} animationProps={{ isLoading, animateOnLoad: true }} />
|
|
87
|
+
);
|
|
88
|
+
};
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
### Example 2: Adding a Clickable Row Action
|
|
92
|
+
|
|
93
|
+
You can make rows clickable to perform actions, such as navigating to a details page or opening a modal.
|
|
94
|
+
|
|
95
|
+
```jsx
|
|
96
|
+
import React from 'react';
|
|
97
|
+
import ResponsiveTable from 'jattac.libs.web.responsive-table';
|
|
98
|
+
|
|
99
|
+
const ClickableRows = () => {
|
|
100
|
+
const columns = [
|
|
101
|
+
{ displayLabel: 'Product', cellRenderer: (row) => row.product },
|
|
102
|
+
{ displayLabel: 'Price', cellRenderer: (row) => `${row.price.toFixed(2)}` },
|
|
103
|
+
];
|
|
104
|
+
|
|
105
|
+
const data = [
|
|
106
|
+
{ id: 1, product: 'Laptop', price: 1200 },
|
|
107
|
+
{ id: 2, product: 'Keyboard', price: 75 },
|
|
108
|
+
];
|
|
109
|
+
|
|
110
|
+
const handleRowClick = (item) => {
|
|
111
|
+
alert(`You clicked on product ID: ${item.id}`);
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
return <ResponsiveTable columnDefinitions={columns} data={data} onRowClick={handleRowClick} />;
|
|
115
|
+
};
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
### Example 3: Custom Cell Rendering
|
|
119
|
+
|
|
120
|
+
You can render any React component inside a cell, allowing for rich content like buttons, links, or status badges.
|
|
121
|
+
|
|
122
|
+
```jsx
|
|
123
|
+
import React from 'react';
|
|
124
|
+
import ResponsiveTable from 'jattac.libs.web.responsive-table';
|
|
125
|
+
|
|
126
|
+
const CustomCells = () => {
|
|
127
|
+
const columns = [
|
|
128
|
+
{ displayLabel: <strong>User</strong>, cellRenderer: (row) => <strong>{row.user}</strong> },
|
|
129
|
+
{
|
|
130
|
+
displayLabel: 'Status',
|
|
131
|
+
cellRenderer: (row) => (
|
|
132
|
+
<span
|
|
133
|
+
style={{
|
|
134
|
+
color: row.status === 'Active' ? 'green' : 'red',
|
|
135
|
+
fontWeight: 'bold',
|
|
136
|
+
}}
|
|
137
|
+
>
|
|
138
|
+
{row.status}
|
|
139
|
+
</span>
|
|
140
|
+
),
|
|
141
|
+
},
|
|
142
|
+
{
|
|
143
|
+
displayLabel: 'Action',
|
|
144
|
+
cellRenderer: (row) => <button onClick={() => alert(`Editing ${row.user}`)}>Edit</button>,
|
|
145
|
+
},
|
|
146
|
+
];
|
|
147
|
+
|
|
148
|
+
const data = [
|
|
149
|
+
{ user: 'Eve', status: 'Active' },
|
|
150
|
+
{ user: 'Frank', status: 'Inactive' },
|
|
151
|
+
];
|
|
152
|
+
|
|
153
|
+
return <ResponsiveTable columnDefinitions={columns} data={data} />;
|
|
154
|
+
};
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
### Example 4: Dynamic and Conditional Columns
|
|
158
|
+
|
|
159
|
+
Columns can be generated dynamically based on your data or application state. This is useful for creating flexible tables that adapt to different datasets.
|
|
160
|
+
|
|
161
|
+
```jsx
|
|
162
|
+
import React from 'react';
|
|
163
|
+
import ResponsiveTable from 'jattac.libs.web.responsive-table';
|
|
164
|
+
|
|
165
|
+
const DynamicColumns = ({ isAdmin }) => {
|
|
166
|
+
// Base columns for all users
|
|
167
|
+
const columns = [
|
|
168
|
+
{ displayLabel: 'File Name', cellRenderer: (row) => row.fileName },
|
|
169
|
+
{ displayLabel: 'Size', cellRenderer: (row) => `${row.size} KB` },
|
|
170
|
+
];
|
|
171
|
+
|
|
172
|
+
// Add an admin-only column conditionally
|
|
173
|
+
if (isAdmin) {
|
|
174
|
+
columns.push({
|
|
175
|
+
displayLabel: 'Admin Actions',
|
|
176
|
+
cellRenderer: (row) => <button onClick={() => alert(`Deleting ${row.fileName}`)}>Delete</button>,
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const data = [
|
|
181
|
+
{ fileName: 'document.pdf', size: 1024 },
|
|
182
|
+
{ fileName: 'image.jpg', size: 512 },
|
|
183
|
+
];
|
|
184
|
+
|
|
185
|
+
return <ResponsiveTable columnDefinitions={columns} data={data} />;
|
|
186
|
+
};
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
### Example 5: Advanced Footer with Labels and Interactivity
|
|
190
|
+
|
|
191
|
+
You can add a footer to display summary information, such as totals or averages. The footer is also responsive and will appear correctly in both desktop and mobile views. With the enhanced footer functionality, you can provide explicit labels for mobile view and add click handlers to footer cells.
|
|
192
|
+
|
|
193
|
+
```jsx
|
|
194
|
+
import React from 'react';
|
|
195
|
+
import ResponsiveTable from 'jattac.libs.web.responsive-table';
|
|
196
|
+
|
|
197
|
+
const TableWithFooter = () => {
|
|
198
|
+
const columns = [
|
|
199
|
+
{ displayLabel: 'Item', cellRenderer: (row) => row.item },
|
|
200
|
+
{ displayLabel: 'Quantity', cellRenderer: (row) => row.quantity },
|
|
201
|
+
{ displayLabel: 'Price', cellRenderer: (row) => `${row.price.toFixed(2)}` },
|
|
202
|
+
];
|
|
203
|
+
|
|
204
|
+
const data = [
|
|
205
|
+
{ item: 'Apples', quantity: 10, price: 1.5 },
|
|
206
|
+
{ item: 'Oranges', quantity: 5, price: 2.0 },
|
|
207
|
+
{ item: 'Bananas', quantity: 15, price: 0.5 },
|
|
208
|
+
];
|
|
209
|
+
|
|
210
|
+
const total = data.reduce((sum, row) => sum + row.quantity * row.price, 0);
|
|
211
|
+
|
|
212
|
+
const footerRows = [
|
|
213
|
+
{
|
|
214
|
+
columns: [
|
|
215
|
+
{
|
|
216
|
+
colSpan: 2,
|
|
217
|
+
cellRenderer: () => <strong>Total:</strong>,
|
|
218
|
+
},
|
|
219
|
+
{
|
|
220
|
+
colSpan: 1,
|
|
221
|
+
displayLabel: 'Total',
|
|
222
|
+
cellRenderer: () => <strong>${total.toFixed(2)}</strong>,
|
|
223
|
+
onCellClick: () => alert('Total clicked!'),
|
|
224
|
+
},
|
|
225
|
+
],
|
|
226
|
+
},
|
|
227
|
+
];
|
|
228
|
+
|
|
229
|
+
return <ResponsiveTable columnDefinitions={columns} data={data} footerRows={footerRows} />;
|
|
230
|
+
};
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
### Example 6: Disabling Page-Level Sticky Header
|
|
234
|
+
|
|
235
|
+
By default, the table header remains fixed to the top of the viewport as the user scrolls down the page. This ensures the column titles are always visible. To disable this behavior and have the header scroll away with the rest of the page, set the `enablePageLevelStickyHeader` prop to `false`.
|
|
236
|
+
|
|
237
|
+
```jsx
|
|
238
|
+
import React from 'react';
|
|
239
|
+
import ResponsiveTable from 'jattac.libs.web.responsive-table';
|
|
240
|
+
|
|
241
|
+
const NonStickyHeaderTable = () => {
|
|
242
|
+
// We need enough data to make the page scroll
|
|
243
|
+
const data = Array.from({ length: 50 }, (_, i) => ({
|
|
244
|
+
id: i + 1,
|
|
245
|
+
item: `Item #${i + 1}`,
|
|
246
|
+
description: 'This is a sample item.',
|
|
247
|
+
}));
|
|
248
|
+
|
|
249
|
+
const columns = [
|
|
250
|
+
{ displayLabel: 'ID', cellRenderer: (row) => row.id },
|
|
251
|
+
{ displayLabel: 'Item', cellRenderer: (row) => row.item },
|
|
252
|
+
{ displayLabel: 'Description', cellRenderer: (row) => row.description },
|
|
253
|
+
];
|
|
254
|
+
|
|
255
|
+
return (
|
|
256
|
+
<div>
|
|
257
|
+
<h1 style={{ height: '50vh', display: 'flex', alignItems: 'center' }}>Scroll down to see the table</h1>
|
|
258
|
+
<ResponsiveTable
|
|
259
|
+
columnDefinitions={columns}
|
|
260
|
+
data={data}
|
|
261
|
+
enablePageLevelStickyHeader={false} // <-- Here's the magic switch!
|
|
262
|
+
/>
|
|
263
|
+
<div style={{ height: '50vh' }} />
|
|
264
|
+
</div>
|
|
265
|
+
);
|
|
266
|
+
};
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
---
|
|
270
|
+
|
|
271
|
+
## Plugin System
|
|
272
|
+
|
|
273
|
+
ResponsiveTable is designed with an extensible plugin system, allowing developers to easily add new functionalities or modify existing behaviors without altering the core component. Plugins can interact with the table's data, render custom UI elements (like headers or footers), and respond to table events.
|
|
274
|
+
|
|
275
|
+
### Plugin Execution Order
|
|
276
|
+
|
|
277
|
+
> **Note:** Plugins process data sequentially in the order they are provided in the `plugins` array. This can have important performance and behavioral implications.
|
|
278
|
+
|
|
279
|
+
For example, consider the `SortPlugin` and `FilterPlugin`.
|
|
280
|
+
|
|
281
|
+
- `plugins={[new SortPlugin(), new FilterPlugin()]}`: This will **sort** the entire dataset first, and then **filter** the sorted data.
|
|
282
|
+
- `plugins={[new FilterPlugin(), new SortPlugin()]}`: This will **filter** the dataset first, and then **sort** the much smaller, filtered result.
|
|
283
|
+
|
|
284
|
+
For the best performance, it is highly recommended to **filter first, then sort**.
|
|
285
|
+
|
|
286
|
+
### How to Use Plugins
|
|
287
|
+
|
|
288
|
+
Plugins are passed to the `ResponsiveTable` component via the `plugins` prop, which accepts an array of `IResponsiveTablePlugin` instances. Some common functionalities, like filtering and infinite scrolling, are provided as built-in plugins that can be enabled via specific props (`filterProps` and `infiniteScrollProps`). When these props are used, the corresponding built-in plugins are automatically initialized if not already provided in the `plugins` array.
|
|
289
|
+
|
|
290
|
+
```jsx
|
|
291
|
+
import React from 'react';
|
|
292
|
+
// Note: All plugins are exported from the main package entry point.
|
|
293
|
+
import ResponsiveTable, { FilterPlugin } from 'jattac.libs.web.responsive-table';
|
|
294
|
+
|
|
295
|
+
const MyTableWithPlugins = () => {
|
|
296
|
+
const columns = [
|
|
297
|
+
{ displayLabel: 'Name', dataKey: 'name', cellRenderer: (row) => row.name, getFilterableValue: (row) => row.name },
|
|
298
|
+
{
|
|
299
|
+
displayLabel: 'Age',
|
|
300
|
+
dataKey: 'age',
|
|
301
|
+
cellRenderer: (row) => row.age,
|
|
302
|
+
getFilterableValue: (row) => row.age.toString(),
|
|
303
|
+
},
|
|
304
|
+
];
|
|
305
|
+
|
|
306
|
+
const data = [
|
|
307
|
+
{ name: 'Alice', age: 32 },
|
|
308
|
+
{ name: 'Bob', age: 28 },
|
|
309
|
+
{ name: 'Charlie', age: 45 },
|
|
310
|
+
];
|
|
311
|
+
|
|
312
|
+
return (
|
|
313
|
+
<ResponsiveTable
|
|
314
|
+
columnDefinitions={columns}
|
|
315
|
+
data={data}
|
|
316
|
+
// Enable built-in filter plugin via props
|
|
317
|
+
filterProps={{ showFilter: true, filterPlaceholder: 'Search by name or age...' }}
|
|
318
|
+
// Or provide a custom instance of the plugin
|
|
319
|
+
// plugins={[new FilterPlugin()]}
|
|
320
|
+
/>
|
|
321
|
+
);
|
|
322
|
+
};
|
|
323
|
+
```
|
|
324
|
+
|
|
325
|
+
### Built-in Plugins
|
|
326
|
+
|
|
327
|
+
#### `SortPlugin`
|
|
328
|
+
|
|
329
|
+
The `SortPlugin` provides powerful, type-safe, and highly customizable column sorting. It adds intuitive UI cues, allowing users to click column headers to sort the data in ascending, descending, or original order.
|
|
330
|
+
|
|
331
|
+
**Enabling the `SortPlugin`:**
|
|
332
|
+
|
|
333
|
+
To use the plugin, you must first import it and provide a generic instance of it to the `plugins` prop. The real power comes from making the plugin instance generic with your data type, which provides type-safety and IDE autocompletion for the sort comparer helpers.
|
|
334
|
+
|
|
335
|
+
```jsx
|
|
336
|
+
import React from 'react';
|
|
337
|
+
import ResponsiveTable, { IResponsiveTableColumnDefinition, SortPlugin } from 'jattac.libs.web.responsive-table';
|
|
338
|
+
|
|
339
|
+
// Define the shape of your data
|
|
340
|
+
interface User {
|
|
341
|
+
id: number;
|
|
342
|
+
name: string;
|
|
343
|
+
signupDate: string;
|
|
344
|
+
logins: number;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// 1. Create a single, generic instance of the plugin.
|
|
348
|
+
const sortPlugin = new SortPlugin<User>({
|
|
349
|
+
initialSortColumn: 'user_logins', // Use the columnId
|
|
350
|
+
initialSortDirection: 'desc',
|
|
351
|
+
});
|
|
352
|
+
|
|
353
|
+
// 2. Define the columns, using the helpers directly from the plugin instance.
|
|
354
|
+
const columnDefinitions: IResponsiveTableColumnDefinition<User>[] = [
|
|
355
|
+
// ... see examples below
|
|
356
|
+
];
|
|
357
|
+
|
|
358
|
+
const UserTable = ({ users }) => (
|
|
359
|
+
<ResponsiveTable
|
|
360
|
+
columnDefinitions={columnDefinitions}
|
|
361
|
+
data={users}
|
|
362
|
+
// 3. Pass the already-configured plugin to the table.
|
|
363
|
+
plugins={[sortPlugin]}
|
|
364
|
+
/>
|
|
365
|
+
);
|
|
366
|
+
```
|
|
367
|
+
|
|
368
|
+
**How to Make Columns Sortable (Opt-In):**
|
|
369
|
+
|
|
370
|
+
A column is made sortable by adding a **`columnId`** and either a `sortComparer` or a `getSortableValue` property to its definition. The `columnId` must be a unique string that identifies the column.
|
|
371
|
+
|
|
372
|
+
- `sortComparer`: A function that defines the exact comparison logic. This is the most powerful option and should be used for complex data types or custom logic.
|
|
373
|
+
- `getSortableValue`: A simpler function that just returns the primitive value (string, number, etc.) to be used in a default comparison.
|
|
374
|
+
|
|
375
|
+
**Example 1: Using Type-Safe Comparer Helpers**
|
|
376
|
+
|
|
377
|
+
The `SortPlugin` instance provides a `comparers` object with pre-built, type-safe helper functions to eliminate boilerplate for common sorting scenarios. This is the recommended approach.
|
|
378
|
+
|
|
379
|
+
```jsx
|
|
380
|
+
const columnDefinitions: IResponsiveTableColumnDefinition<User>[] = [
|
|
381
|
+
{
|
|
382
|
+
columnId: 'user_name',
|
|
383
|
+
displayLabel: 'Name',
|
|
384
|
+
dataKey: 'name',
|
|
385
|
+
cellRenderer: (user) => user.name,
|
|
386
|
+
// The plugin instance itself provides the type-safe helpers.
|
|
387
|
+
// The string 'name' is fully type-checked against the User interface.
|
|
388
|
+
sortComparer: sortPlugin.comparers.caseInsensitiveString('name'),
|
|
389
|
+
},
|
|
390
|
+
{
|
|
391
|
+
columnId: 'user_signup_date',
|
|
392
|
+
displayLabel: 'Signup Date',
|
|
393
|
+
dataKey: 'signupDate',
|
|
394
|
+
cellRenderer: (user) => new Date(user.signupDate).toLocaleDateString(),
|
|
395
|
+
// IDE autocompletion for 'signupDate' works perfectly.
|
|
396
|
+
sortComparer: sortPlugin.comparers.date('signupDate'),
|
|
397
|
+
},
|
|
398
|
+
{
|
|
399
|
+
columnId: 'user_logins',
|
|
400
|
+
displayLabel: 'Logins',
|
|
401
|
+
dataKey: 'logins',
|
|
402
|
+
cellRenderer: (user) => user.logins,
|
|
403
|
+
sortComparer: sortPlugin.comparers.numeric('logins'),
|
|
404
|
+
},
|
|
405
|
+
{
|
|
406
|
+
columnId: 'user_actions',
|
|
407
|
+
displayLabel: 'Actions',
|
|
408
|
+
// This column is NOT sortable because it has no sort-related properties.
|
|
409
|
+
cellRenderer: (user) => <button>View</button>,
|
|
410
|
+
},
|
|
411
|
+
];
|
|
412
|
+
```
|
|
413
|
+
|
|
414
|
+
**Example 2: Writing a Custom `sortComparer` for a Computed Column**
|
|
415
|
+
|
|
416
|
+
> **Important:** When writing a custom `sortComparer`, you **must** include all three parameters (`a`, `b`, and `direction`) in your function signature. Forgetting the `direction` parameter will cause descending sorts to fail. The IDE is configured to provide a warning if you forget, and the developer console will also show a warning at runtime.
|
|
417
|
+
|
|
418
|
+
For unique requirements, you can write your own comparison function. Notice how `columnId` is used without a `dataKey`.
|
|
419
|
+
|
|
420
|
+
```jsx
|
|
421
|
+
const columnDefinitions: IResponsiveTableColumnDefinition<User>[] = [
|
|
422
|
+
{
|
|
423
|
+
columnId: 'user_name_custom',
|
|
424
|
+
displayLabel: 'Name',
|
|
425
|
+
cellRenderer: (user) => user.name,
|
|
426
|
+
// Writing custom logic for a case-sensitive sort
|
|
427
|
+
sortComparer: (a, b, direction) => {
|
|
428
|
+
const nameA = a.name; // No .toLowerCase()
|
|
429
|
+
const nameB = b.name;
|
|
430
|
+
if (nameA < nameB) return direction === 'asc' ? -1 : 1;
|
|
431
|
+
if (nameA > nameB) return direction === 'asc' ? 1 : -1;
|
|
432
|
+
return 0;
|
|
433
|
+
},
|
|
434
|
+
},
|
|
435
|
+
];
|
|
436
|
+
```
|
|
437
|
+
|
|
438
|
+
**Example 3: Using `getSortableValue` for Simple Cases**
|
|
439
|
+
|
|
440
|
+
If you don't need special logic, `getSortableValue` is a concise way to enable default sorting on a property.
|
|
441
|
+
|
|
442
|
+
```jsx
|
|
443
|
+
const columnDefinitions: IResponsiveTableColumnDefinition<User>[] = [
|
|
444
|
+
{
|
|
445
|
+
columnId: 'user_logins_simple',
|
|
446
|
+
displayLabel: 'Logins',
|
|
447
|
+
dataKey: 'logins',
|
|
448
|
+
cellRenderer: (user) => user.logins,
|
|
449
|
+
// This enables a simple, default numerical sort on the 'logins' property.
|
|
450
|
+
getSortableValue: (user) => user.logins,
|
|
451
|
+
},
|
|
452
|
+
];
|
|
453
|
+
```
|
|
454
|
+
|
|
455
|
+
**Plugin Options (via `new SortPlugin(options)`):**
|
|
456
|
+
|
|
457
|
+
| Prop | Type | Description |
|
|
458
|
+
| ---------------------- | ----------------- | ---------------------------------------------------- |
|
|
459
|
+
| `initialSortColumn` | `string` | The `columnId` of the column to sort by initially. |
|
|
460
|
+
| `initialSortDirection` | `'asc' \| 'desc'` | The direction for the initial sort. |
|
|
461
|
+
|
|
462
|
+
**`SortPlugin.comparers` API:**
|
|
463
|
+
|
|
464
|
+
The `comparers` object on your `SortPlugin` instance provides the following helper methods. Each method is a factory that takes a `dataKey` (which is type-checked against your data model) and returns a `sortComparer` function.
|
|
465
|
+
|
|
466
|
+
| Method | Description |
|
|
467
|
+
| -------------------------------- | ----------------------------------------------------------------------------- |
|
|
468
|
+
| `numeric(dataKey)` | Performs a standard numerical sort. |
|
|
469
|
+
| `caseInsensitiveString(dataKey)` | Performs a case-insensitive alphabetical sort. |
|
|
470
|
+
| `date(dataKey)` | Correctly sorts dates, assuming the data is a valid date string or timestamp. |
|
|
471
|
+
|
|
472
|
+
#### `FilterPlugin`
|
|
473
|
+
|
|
474
|
+
> **Warning: Incompatible with Infinite Scroll**
|
|
475
|
+
> The `FilterPlugin` is a client-side utility that only operates on data currently loaded in the browser. It is **not compatible** with the `InfiniteScrollPlugin`, as it cannot search data that has not yet been fetched from the server. For tables using infinite scroll, filtering logic must be implemented server-side by your application and passed into the `onLoadMore` function.
|
|
476
|
+
|
|
477
|
+
Provides a search input to filter table data. It can be enabled by setting `filterProps.showFilter` to `true` on the `ResponsiveTable` component. For columns to be filterable, you must provide a `getFilterableValue` function in their `IResponsiveTableColumnDefinition`.
|
|
478
|
+
|
|
479
|
+
**Props for `FilterPlugin` (via `filterProps` on `ResponsiveTable`):**
|
|
480
|
+
|
|
481
|
+
| Prop | Type | Description |
|
|
482
|
+
| ------------------- | --------- | --------------------------------------------------------------- |
|
|
483
|
+
| `showFilter` | `boolean` | If `true`, displays a filter input field above the table. |
|
|
484
|
+
| `filterPlaceholder` | `string` | Placeholder text for the filter input. Defaults to "Search...". |
|
|
485
|
+
|
|
486
|
+
**Example with `FilterPlugin`:**
|
|
487
|
+
|
|
488
|
+
```jsx
|
|
489
|
+
import React from 'react';
|
|
490
|
+
import ResponsiveTable from 'jattac.libs.web.responsive-table';
|
|
491
|
+
|
|
492
|
+
const FilterableTable = () => {
|
|
493
|
+
const initialData = [
|
|
494
|
+
{ id: 1, name: 'Alice', email: 'alice@example.com' },
|
|
495
|
+
{ id: 2, name: 'Bob', email: 'bob@example.com' },
|
|
496
|
+
{ id: 3, name: 'Charlie', email: 'charlie@example.com' },
|
|
497
|
+
{ id: 4, name: 'David', email: 'david@example.com' },
|
|
498
|
+
];
|
|
499
|
+
|
|
500
|
+
const columns = [
|
|
501
|
+
{ displayLabel: 'ID', cellRenderer: (row) => row.id, getFilterableValue: (row) => row.id.toString() },
|
|
502
|
+
{ displayLabel: 'Name', cellRenderer: (row) => row.name, getFilterableValue: (row) => row.name },
|
|
503
|
+
{ displayLabel: 'Email', cellRenderer: (row) => row.email, getFilterableValue: (row) => row.email },
|
|
504
|
+
];
|
|
505
|
+
|
|
506
|
+
return (
|
|
507
|
+
<ResponsiveTable
|
|
508
|
+
columnDefinitions={columns}
|
|
509
|
+
data={initialData}
|
|
510
|
+
filterProps={{ showFilter: true, filterPlaceholder: 'Filter users...' }}
|
|
511
|
+
/>
|
|
512
|
+
);
|
|
513
|
+
};
|
|
514
|
+
```
|
|
515
|
+
|
|
516
|
+
#### Infinite Scroll
|
|
517
|
+
|
|
518
|
+
> **Warning: Incompatible with Client-Side Filtering**
|
|
519
|
+
> The infinite scroll feature fetches data in chunks from a server. It is **not compatible** with the client-side `FilterPlugin`. For filtering to work correctly with infinite scroll, you must implement the filtering logic on your server and have the `onLoadMore` function fetch data that is already filtered.
|
|
520
|
+
|
|
521
|
+
Enables a simple infinite scroll for loading more data as the user scrolls to the bottom of the table. This is useful for progressively loading data from an API without needing traditional pagination buttons. When enabled, the `ResponsiveTable` renders a specialized internal component optimized for this purpose.
|
|
522
|
+
|
|
523
|
+
> **Important:** To enable infinite scroll, you **must** give the table a bounded height. This is done by passing the `maxHeight` prop to the `<ResponsiveTable>`. This prop creates a scrollable container for the table body, which is required for the scroll detection to work.
|
|
524
|
+
|
|
525
|
+
> **Performance Note:** This implementation renders all loaded rows into the DOM to guarantee correct column alignment and simplicity. It is **not a virtualized list**. For extremely large datasets (many thousands of rows), performance may degrade as more rows are loaded. It is best suited for scenarios where loading a few hundred up to a couple thousand rows is expected.
|
|
526
|
+
|
|
527
|
+
**Configuration (via `infiniteScrollProps` on `ResponsiveTable`):**
|
|
528
|
+
|
|
529
|
+
| Prop | Type | Description |
|
|
530
|
+
| ---------------------- | ---------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
531
|
+
| `enableInfiniteScroll` | `boolean` | If `true`, enables infinite scrolling. |
|
|
532
|
+
| `hasMore` | `boolean` | **Optional.** Controls the loading indicator. If omitted, the component infers this state automatically by checking if `onLoadMore` returns an empty array or `null`. If provided, your app is responsible for managing this state. |
|
|
533
|
+
| `onLoadMore` | `(currentData: TData[]) => Promise<TData[] | null>` | A callback function that fires when the user scrolls near the end. It should fetch the next page of data and return it in a Promise. The component will stop trying to load more when this function returns `null` or an empty array. |
|
|
534
|
+
| `loadingMoreComponent` | `ReactNode` | A custom component to display at the bottom while new data is being loaded. Defaults to a spinner animation. |
|
|
535
|
+
| `noMoreDataComponent` | `ReactNode` | A custom component to display at the bottom when `hasMore` is `false`. Defaults to a "No more data" message. |
|
|
536
|
+
|
|
537
|
+
**Comprehensive Example:**
|
|
538
|
+
|
|
539
|
+
Here is a complete example showing how to use the infinite scroll feature. The parent component only needs to provide a function that fetches the next page of data.
|
|
540
|
+
|
|
541
|
+
```jsx
|
|
542
|
+
import React, { useState, useCallback } from 'react';
|
|
543
|
+
import ResponsiveTable from 'jattac.libs.web.responsive-table';
|
|
544
|
+
|
|
545
|
+
// Define the shape of our data items
|
|
546
|
+
interface DataItem {
|
|
547
|
+
id: number;
|
|
548
|
+
value: string;
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
// This is a mock API function to simulate fetching data.
|
|
552
|
+
// In a real app, this would be an actual network request.
|
|
553
|
+
const fetchData = async (page: number): Promise<DataItem[]> => {
|
|
554
|
+
console.log(`Fetching page: ${page}`);
|
|
555
|
+
return new Promise((resolve) => {
|
|
556
|
+
setTimeout(() => {
|
|
557
|
+
// Return an empty array for pages > 5 to simulate the end of the data
|
|
558
|
+
if (page > 5) {
|
|
559
|
+
resolve([]);
|
|
560
|
+
return;
|
|
561
|
+
}
|
|
562
|
+
// Generate 20 new items for the current page
|
|
563
|
+
const newData = Array.from({ length: 20 }, (_, i) => ({
|
|
564
|
+
id: page * 20 + i,
|
|
565
|
+
value: `Item #${page * 20 + i}`,
|
|
566
|
+
}));
|
|
567
|
+
resolve(newData);
|
|
568
|
+
}, 500); // Simulate network latency
|
|
569
|
+
});
|
|
570
|
+
};
|
|
571
|
+
|
|
572
|
+
const InfiniteScrollExample = () => {
|
|
573
|
+
// Keep track of the next page to fetch.
|
|
574
|
+
const [nextPage, setNextPage] = useState(0);
|
|
575
|
+
|
|
576
|
+
// The onLoadMore function is now much simpler.
|
|
577
|
+
// It just needs to fetch the data and return it.
|
|
578
|
+
// The table will handle appending the data and managing the `hasMore` state internally.
|
|
579
|
+
const loadMoreItems = useCallback(async () => {
|
|
580
|
+
const newItems = await fetchData(nextPage);
|
|
581
|
+
setNextPage((prevPage) => prevPage + 1);
|
|
582
|
+
return newItems; // <-- Simply return the new items
|
|
583
|
+
}, [nextPage]);
|
|
584
|
+
|
|
585
|
+
const columns = [
|
|
586
|
+
{ displayLabel: 'ID', dataKey: 'id', cellRenderer: (row) => row.id },
|
|
587
|
+
{ displayLabel: 'Value', dataKey: 'value', cellRenderer: (row) => row.value },
|
|
588
|
+
];
|
|
589
|
+
|
|
590
|
+
return (
|
|
591
|
+
// The table MUST be inside a container with a defined height.
|
|
592
|
+
<div style={{ height: '400px' }}>
|
|
593
|
+
<ResponsiveTable
|
|
594
|
+
columnDefinitions={columns}
|
|
595
|
+
data={[]} // Start with an empty array of initial data
|
|
596
|
+
maxHeight="100%"
|
|
597
|
+
infiniteScrollProps={{
|
|
598
|
+
enableInfiniteScroll: true,
|
|
599
|
+
onLoadMore: loadMoreItems,
|
|
600
|
+
|
|
601
|
+
loadingMoreComponent: <h4>Loading more items...</h4>,
|
|
602
|
+
noMoreDataComponent: <p>You've reached the end!</p>,
|
|
603
|
+
}}
|
|
604
|
+
/>
|
|
605
|
+
</div>
|
|
606
|
+
);
|
|
607
|
+
};
|
|
608
|
+
```
|
|
609
|
+
|
|
610
|
+
---
|
|
611
|
+
|
|
612
|
+
## API Reference
|
|
613
|
+
|
|
614
|
+
### `ResponsiveTable` Props
|
|
615
|
+
|
|
616
|
+
| Prop | Type | Required | Description |
|
|
617
|
+
| ----------------------------- | ------------------------------------ | -------- | --------------------------------------------------------------------------------------------------- |
|
|
618
|
+
| `columnDefinitions` | `IResponsiveTableColumnDefinition[]` | Yes | An array of objects defining the table columns. Can also accept a function for dynamic column generation. |
|
|
619
|
+
| `data` | `TData[]` | Yes | An array of data objects to populate the table rows. |
|
|
620
|
+
| `footerRows` | `IFooterRowDefinition[]` | No | An array of objects defining the table footer. |
|
|
621
|
+
| `onRowClick` | `(item: TData) => void` | No | A callback function that is triggered when a row is clicked. |
|
|
622
|
+
| `noDataComponent` | `ReactNode` | No | A custom component to display when there is no data. |
|
|
623
|
+
| `maxHeight` | `string` | No | Sets a maximum height for the table body, making it scrollable. |
|
|
624
|
+
| `mobileBreakpoint` | `number` | No | The pixel width at which the table switches to the mobile view. Defaults to `600`. |
|
|
625
|
+
| `enablePageLevelStickyHeader` | `boolean` | No | If `false`, disables the header from sticking to the top of the page on scroll. Defaults to `true`. |
|
|
626
|
+
| `plugins` | `IResponsiveTablePlugin<TData>[]` | No | An array of plugin instances to extend table functionality. |
|
|
627
|
+
| `infiniteScrollProps` | `object` | No | Configuration for the infinite scroll feature. When enabled, a specialized component handles data loading. |
|
|
628
|
+
| `filterProps` | `object` | No | Configuration for the built-in filter plugin. |
|
|
629
|
+
| `animationProps` | `object` | No | Configuration for animations, including `isLoading` and `animateOnLoad`. |
|
|
630
|
+
|
|
631
|
+
### `IResponsiveTableColumnDefinition<TData>`
|
|
632
|
+
|
|
633
|
+
| Property | Type | Required | Description |
|
|
634
|
+
| -------------------- | ------------------------------------------------------------ | -------- | ---------------------------------------------------------------------------------------- |
|
|
635
|
+
| `displayLabel` | `ReactNode` | Yes | The label displayed in the table header (can be a string or any React component). |
|
|
636
|
+
| `cellRenderer` | `(row: TData) => ReactNode` | Yes | A function that returns the content to be rendered in the cell. |
|
|
637
|
+
| `columnId` | `string` | No | A unique string to identify the column. **Required** if the column is sortable. |
|
|
638
|
+
| `dataKey` | `keyof TData` | No | A key to match the column to a property in the data object. |
|
|
639
|
+
| `interactivity` | `object` | No | An object to define header interactivity (`onHeaderClick`, `id`, `className`). |
|
|
640
|
+
| `getFilterableValue` | `(row: TData) => string \| number` | No | A function that returns the string or number value to be used for filtering this column. |
|
|
641
|
+
| `getSortableValue` | `(row: TData) => any` | No | A function that returns a primitive value from a row to be used for default sorting. |
|
|
642
|
+
| `sortComparer` | `(a: TData, b: TData, direction: 'asc' \| 'desc') => number` | No | A function that provides the precise comparison logic for sorting a column. |
|
|
643
|
+
|
|
644
|
+
### `IFooterRowDefinition`
|
|
645
|
+
|
|
646
|
+
| Property | Type | Required | Description |
|
|
647
|
+
| --------- | --------------------------- | -------- | -------------------------------------------------- |
|
|
648
|
+
| `columns` | `IFooterColumnDefinition[]` | Yes | An array of column definitions for the footer row. |
|
|
649
|
+
|
|
650
|
+
### `IFooterColumnDefinition`
|
|
651
|
+
|
|
652
|
+
| Property | Type | Required | Description |
|
|
653
|
+
| -------------- | ----------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
654
|
+
| `colSpan` | `number` | Yes | The number of columns the footer cell should span. |
|
|
655
|
+
| `cellRenderer` | `() => ReactNode` | Yes | A function that returns the content for the footer cell. |
|
|
656
|
+
| `displayLabel` | `ReactNode` | No | An optional, explicit label for the footer cell. In mobile view, if `colSpan` is 1 and this is not provided, the corresponding column header will be used as a fallback. This is required for `colSpan` > 1 if you want a label to be displayed. |
|
|
657
|
+
| `onCellClick` | `() => void` | No | An optional click handler for the footer cell. |
|
|
658
|
+
| `className` | `string` | No | Optional class name for custom styling of the footer cell. |
|
|
659
|
+
|
|
660
|
+
## License
|
|
661
|
+
|
|
662
|
+
This project is licensed under the MIT License.
|