0
# Utilities and Constants
1
2
Helper constants, utilities, and configuration options for advanced grid customization and performance optimization.
3
4
## Capabilities
5
6
### Constants Collection
7
8
Built-in constants for configuring grid behavior and handling grid events.
9
10
```javascript { .api }
11
const _constants = {
12
/** Cell navigation modes */
13
CellNavigationMode: {
14
NONE: 'none';
15
CHANGE_ROW: 'changeRow';
16
LOOP_OVER_ROW: 'loopOverRow';
17
};
18
19
/** Grid update action types */
20
UpdateActions: {
21
CELL_UPDATE: 'CELL_UPDATE';
22
COLUMN_FILL: 'COLUMN_FILL';
23
COPY_PASTE: 'COPY_PASTE';
24
CELL_DRAG: 'CELL_DRAG';
25
};
26
27
/** Event type constants */
28
EventTypes: {
29
SELECT_CELL: 'SELECT_CELL';
30
SELECT_START: 'SELECT_START';
31
SELECT_UPDATE: 'SELECT_UPDATE';
32
SELECT_END: 'SELECT_END';
33
DRAG_ENTER: 'DRAG_ENTER';
34
SCROLL_TO_COLUMN: 'SCROLL_TO_COLUMN';
35
};
36
37
/** Header row type constants */
38
HeaderRowType: {
39
HEADER: 'header';
40
FILTER: 'filter';
41
};
42
43
/** Cell expansion icons */
44
CellExpand: {
45
DOWN_TRIANGLE: '▼';
46
RIGHT_TRIANGLE: '▶';
47
};
48
49
/** Drag and drop item types */
50
DragItemTypes: {
51
Column: 'column';
52
};
53
};
54
```
55
56
### CellNavigationMode
57
58
Constants for configuring cell navigation behavior.
59
60
```javascript { .api }
61
/**
62
* Cell navigation mode constants
63
* Controls how keyboard navigation behaves between cells
64
*/
65
const CellNavigationMode = {
66
/** No automatic navigation between cells */
67
NONE: 'none';
68
/** Tab key loops within the current row */
69
LOOP_OVER_ROW: 'loopOverRow';
70
/** Tab key moves to next/previous row when reaching row end */
71
CHANGE_ROW: 'changeRow';
72
};
73
```
74
75
**Usage Example:**
76
77
```javascript
78
import ReactDataGrid, { _constants } from 'react-data-grid';
79
80
const NavigationGrid = () => {
81
return (
82
<ReactDataGrid
83
columns={columns}
84
rowGetter={i => rows[i]}
85
rowsCount={rows.length}
86
minHeight={400}
87
enableCellSelect={true}
88
cellNavigationMode={_constants.CellNavigationMode.CHANGE_ROW}
89
/>
90
);
91
};
92
```
93
94
### UpdateActions
95
96
Constants identifying different types of grid data updates.
97
98
```javascript { .api }
99
/**
100
* Update action type constants
101
* Used in onGridRowsUpdated events to identify update source
102
*/
103
const UpdateActions = {
104
/** Single cell edit via editor */
105
CELL_UPDATE: 'CELL_UPDATE';
106
/** Multiple cells updated via column fill/drag down */
107
COLUMN_FILL: 'COLUMN_FILL';
108
/** Cells updated via copy/paste operation */
109
COPY_PASTE: 'COPY_PASTE';
110
/** Cells updated via drag and drop */
111
CELL_DRAG: 'CELL_DRAG';
112
};
113
```
114
115
**Usage Example:**
116
117
```javascript
118
import ReactDataGrid, { _constants } from 'react-data-grid';
119
120
const UpdateHandlingGrid = () => {
121
const handleGridRowsUpdated = ({ fromRow, toRow, updated, action }) => {
122
console.log('Update action:', action);
123
124
switch (action) {
125
case _constants.UpdateActions.CELL_UPDATE:
126
console.log('Single cell updated');
127
break;
128
case _constants.UpdateActions.COLUMN_FILL:
129
console.log('Column fill operation');
130
break;
131
case _constants.UpdateActions.COPY_PASTE:
132
console.log('Copy/paste operation');
133
break;
134
case _constants.UpdateActions.CELL_DRAG:
135
console.log('Drag operation');
136
break;
137
}
138
139
// Handle the update
140
updateRows(fromRow, toRow, updated);
141
};
142
143
return (
144
<ReactDataGrid
145
columns={columns}
146
rowGetter={i => rows[i]}
147
rowsCount={rows.length}
148
minHeight={400}
149
enableCellSelect={true}
150
onGridRowsUpdated={handleGridRowsUpdated}
151
/>
152
);
153
};
154
```
155
156
### EventTypes
157
158
Constants for internal grid event types.
159
160
```javascript { .api }
161
/**
162
* Grid event type constants
163
* Used internally for grid event system
164
*/
165
const EventTypes = {
166
/** Cell selection event */
167
SELECT_CELL: 'SELECT_CELL';
168
/** Selection range start event */
169
SELECT_START: 'SELECT_START';
170
/** Selection range update event */
171
SELECT_UPDATE: 'SELECT_UPDATE';
172
/** Selection range end event */
173
SELECT_END: 'SELECT_END';
174
/** Drag enter event */
175
DRAG_ENTER: 'DRAG_ENTER';
176
/** Scroll to column event */
177
SCROLL_TO_COLUMN: 'SCROLL_TO_COLUMN';
178
};
179
```
180
181
### Row Comparison Utility
182
183
Performance optimization utility for determining when rows should re-render.
184
185
```javascript { .api }
186
/**
187
* Row comparison utility for performance optimization
188
* Determines whether a row component should update based on prop changes
189
* @param nextProps - New props for the row
190
* @param currentProps - Current props for the row
191
* @returns boolean indicating whether the row should update
192
*/
193
const RowComparer: (nextProps: any, currentProps: any) => boolean;
194
```
195
196
**Usage Example:**
197
198
```javascript
199
import React, { memo } from 'react';
200
import ReactDataGrid, { RowComparer } from 'react-data-grid';
201
202
// Optimized row component using RowComparer
203
const OptimizedRow = memo((props) => {
204
return <Row {...props} />;
205
}, RowComparer);
206
207
const PerformanceOptimizedGrid = () => {
208
return (
209
<ReactDataGrid
210
columns={columns}
211
rowGetter={i => rows[i]}
212
rowsCount={rows.length}
213
minHeight={400}
214
rowComponent={OptimizedRow}
215
/>
216
);
217
};
218
```
219
220
### Helper Utilities
221
222
Test utilities and helper functions for grid development and testing.
223
224
```javascript { .api }
225
const _helpers = {
226
/** Test utilities for grid components */
227
test: {
228
/** Helper utilities for creating grid props in tests */
229
GridPropHelpers: {
230
/** Create basic column definitions for testing */
231
createColumns: (count: number) => Column[];
232
/** Create basic row data for testing */
233
createRows: (count: number, columns: Column[]) => any[];
234
/** Create minimal grid props for testing */
235
createGridProps: (overrides?: Partial<ReactDataGridProps>) => ReactDataGridProps;
236
};
237
};
238
};
239
```
240
241
**Testing Example:**
242
243
```javascript
244
import { _helpers } from 'react-data-grid';
245
import { render } from '@testing-library/react';
246
247
const { GridPropHelpers } = _helpers.test;
248
249
describe('Grid Tests', () => {
250
test('renders basic grid', () => {
251
const columns = GridPropHelpers.createColumns(3);
252
const rows = GridPropHelpers.createRows(10, columns);
253
const props = GridPropHelpers.createGridProps({
254
columns,
255
rowGetter: i => rows[i],
256
rowsCount: rows.length
257
});
258
259
const { container } = render(<ReactDataGrid {...props} />);
260
expect(container).toBeInTheDocument();
261
});
262
});
263
```
264
265
### Column and Shape Utilities
266
267
PropTypes shapes and validation helpers for column definitions.
268
269
```javascript { .api }
270
const shapes = {
271
/** PropTypes shape for column definitions */
272
Column: PropTypes.shape({
273
key: PropTypes.string.isRequired,
274
name: PropTypes.node.isRequired,
275
width: PropTypes.number,
276
resizable: PropTypes.bool,
277
sortable: PropTypes.bool,
278
filterable: PropTypes.bool,
279
editable: PropTypes.bool,
280
formatter: PropTypes.node,
281
editor: PropTypes.node,
282
headerRenderer: PropTypes.node,
283
frozen: PropTypes.bool,
284
events: PropTypes.object
285
});
286
};
287
```
288
289
### Utility Functions
290
291
Additional utility functions for common grid operations.
292
293
```javascript { .api }
294
/**
295
* Utility functions for grid operations
296
*/
297
interface GridUtils {
298
/** Calculate column widths based on content */
299
calculateColumnWidths: (columns: Column[], rows: any[]) => Column[];
300
301
/** Sort rows by column */
302
sortRows: (rows: any[], sortColumn: string, sortDirection: SortDirection) => any[];
303
304
/** Filter rows based on filter criteria */
305
filterRows: (rows: any[], filters: Filter[]) => any[];
306
307
/** Export grid data to CSV */
308
exportToCSV: (columns: Column[], rows: any[], filename?: string) => void;
309
310
/** Import CSV data to grid format */
311
importFromCSV: (csvData: string, columns: Column[]) => any[];
312
}
313
```
314
315
**Utility Usage Examples:**
316
317
```javascript
318
import ReactDataGrid, { _constants } from 'react-data-grid';
319
320
// Advanced grid with multiple utilities
321
const AdvancedUtilityGrid = () => {
322
const [rows, setRows] = useState(initialRows);
323
const [sortColumn, setSortColumn] = useState('');
324
const [sortDirection, setSortDirection] = useState('NONE');
325
const [filters, setFilters] = useState([]);
326
327
// Custom sort implementation
328
const handleGridSort = (columnKey, direction) => {
329
setSortColumn(columnKey);
330
setSortDirection(direction);
331
332
const sortedRows = [...rows].sort((a, b) => {
333
const aValue = a[columnKey];
334
const bValue = b[columnKey];
335
336
if (direction === 'ASC') {
337
return aValue < bValue ? -1 : aValue > bValue ? 1 : 0;
338
} else {
339
return aValue > bValue ? -1 : aValue < bValue ? 1 : 0;
340
}
341
});
342
343
setRows(sortedRows);
344
};
345
346
// Export functionality
347
const exportData = () => {
348
const csv = convertToCSV(columns, rows);
349
downloadCSV(csv, 'grid-data.csv');
350
};
351
352
// Filter functionality
353
const handleFilter = (filter) => {
354
const newFilters = [...filters, filter];
355
setFilters(newFilters);
356
357
const filteredRows = initialRows.filter(row => {
358
return newFilters.every(f => {
359
const cellValue = String(row[f.columnKey]).toLowerCase();
360
const filterTerm = f.filterTerm.toLowerCase();
361
return cellValue.includes(filterTerm);
362
});
363
});
364
365
setRows(filteredRows);
366
};
367
368
return (
369
<div>
370
<div style={{ marginBottom: '10px' }}>
371
<button onClick={exportData}>Export to CSV</button>
372
<span style={{ marginLeft: '20px' }}>
373
Showing {rows.length} of {initialRows.length} rows
374
</span>
375
</div>
376
377
<ReactDataGrid
378
columns={columns}
379
rowGetter={i => rows[i]}
380
rowsCount={rows.length}
381
minHeight={400}
382
enableCellSelect={true}
383
cellNavigationMode={_constants.CellNavigationMode.CHANGE_ROW}
384
sortColumn={sortColumn}
385
sortDirection={sortDirection}
386
onGridSort={handleGridSort}
387
onFilter={handleFilter}
388
onGridRowsUpdated={({ action, ...args }) => {
389
console.log('Update action:', action);
390
if (action === _constants.UpdateActions.COPY_PASTE) {
391
console.log('Paste operation detected');
392
}
393
handleRowUpdate(args);
394
}}
395
/>
396
</div>
397
);
398
};
399
400
// Helper functions
401
const convertToCSV = (columns, rows) => {
402
const headers = columns.map(col => col.name).join(',');
403
const csvRows = rows.map(row =>
404
columns.map(col => JSON.stringify(row[col.key] || '')).join(',')
405
);
406
return [headers, ...csvRows].join('\n');
407
};
408
409
const downloadCSV = (csv, filename) => {
410
const blob = new Blob([csv], { type: 'text/csv' });
411
const url = window.URL.createObjectURL(blob);
412
const a = document.createElement('a');
413
a.href = url;
414
a.download = filename;
415
a.click();
416
window.URL.revokeObjectURL(url);
417
};
418
```
419
420
### Performance Optimization Utilities
421
422
Utilities and patterns for optimizing grid performance with large datasets.
423
424
```javascript
425
// Virtual scrolling configuration
426
const largeDatasetGrid = {
427
// Overscan configuration for virtual scrolling
428
overScan: {
429
colsStart: 2, // Columns to render before viewport
430
colsEnd: 2, // Columns to render after viewport
431
rowsStart: 5, // Rows to render before viewport
432
rowsEnd: 5 // Rows to render after viewport
433
}
434
};
435
436
// Memory-efficient row getter
437
const memoizedRowGetter = useMemo(() => {
438
const cache = new Map();
439
return (index) => {
440
if (!cache.has(index)) {
441
cache.set(index, processRowData(rawData[index]));
442
}
443
return cache.get(index);
444
};
445
}, [rawData]);
446
447
// Optimized column definitions
448
const optimizedColumns = useMemo(() =>
449
columns.map(col => ({
450
...col,
451
formatter: col.formatter ? memo(col.formatter) : undefined
452
})),
453
[columns]
454
);
455
```
456
457
### Configuration Presets
458
459
Common configuration presets for different use cases.
460
461
```javascript
462
// Preset configurations
463
const GridPresets = {
464
// Basic read-only grid
465
ReadOnly: {
466
enableCellSelect: false,
467
cellNavigationMode: _constants.CellNavigationMode.NONE
468
},
469
470
// Excel-like editing grid
471
ExcelLike: {
472
enableCellSelect: true,
473
cellNavigationMode: _constants.CellNavigationMode.CHANGE_ROW,
474
enableCellAutoFocus: true
475
},
476
477
// Selection-focused grid
478
Selection: {
479
enableCellSelect: true,
480
rowSelection: {
481
showCheckbox: true,
482
enableShiftSelect: true
483
}
484
},
485
486
// Performance-optimized for large datasets
487
HighPerformance: {
488
enableCellAutoFocus: false,
489
overScan: { colsStart: 1, colsEnd: 1, rowsStart: 2, rowsEnd: 2 }
490
}
491
};
492
```