0
# API Reference
1
2
The API reference system provides imperative control over the data grid through React hooks and API objects. This enables programmatic manipulation of grid state, data, and behavior.
3
4
## Capabilities
5
6
### API Reference Hook
7
8
Hook for creating and managing grid API references for imperative control.
9
10
```typescript { .api }
11
/**
12
* Creates an API reference for programmatic grid control
13
* The returned ref can be passed to the DataGrid component
14
* @returns ApiRef object for accessing grid methods and state
15
*/
16
function useApiRef(): ApiRef;
17
18
/**
19
* API reference type - mutable ref containing the grid API
20
* Provides access to all grid methods and event subscription
21
*/
22
type ApiRef = React.MutableRefObject<GridApi>;
23
```
24
25
**Usage Examples:**
26
27
```typescript
28
import React from "react";
29
import { DataGrid, useApiRef } from "@material-ui/data-grid";
30
31
function ApiControlledGrid() {
32
const apiRef = useApiRef();
33
34
const selectFirstRow = () => {
35
if (apiRef.current && rows.length > 0) {
36
apiRef.current.selectRow(rows[0].id);
37
}
38
};
39
40
const clearSelection = () => {
41
if (apiRef.current) {
42
apiRef.current.selectRows([]);
43
}
44
};
45
46
const scrollToTop = () => {
47
if (apiRef.current) {
48
apiRef.current.scrollToIndexes({ rowIndex: 0, colIndex: 0 });
49
}
50
};
51
52
return (
53
<div>
54
<div style={{ marginBottom: "10px" }}>
55
<button onClick={selectFirstRow}>Select First Row</button>
56
<button onClick={clearSelection}>Clear Selection</button>
57
<button onClick={scrollToTop}>Scroll to Top</button>
58
</div>
59
<div style={{ height: 600, width: "100%" }}>
60
<DataGrid
61
apiRef={apiRef}
62
rows={rows}
63
columns={columns}
64
checkboxSelection
65
/>
66
</div>
67
</div>
68
);
69
}
70
```
71
72
### Grid API Interface
73
74
Complete API interface providing access to all grid functionality and state.
75
76
```typescript { .api }
77
/**
78
* Complete Grid API interface combining all sub-APIs
79
* Provides comprehensive programmatic control over grid behavior
80
*/
81
interface GridApi extends
82
CoreApi,
83
EventsApi,
84
RowApi,
85
ColumnApi,
86
SelectionApi,
87
SortApi,
88
VirtualizationApi,
89
PaginationApi {
90
// Combined interface with all grid capabilities
91
}
92
```
93
94
### Core API
95
96
Essential grid methods for basic functionality and state management.
97
98
```typescript { .api }
99
/**
100
* Core API methods for basic grid operations
101
* Includes initialization, error handling, and general utilities
102
*/
103
interface CoreApi extends EventEmitter {
104
/** Property indicating if grid EventEmitter is initialized */
105
isInitialised: boolean;
106
107
/** Register event handler and return unsubscribe function */
108
subscribeEvent: (event: string, handler: (param: any) => void) => () => void;
109
110
/** Emit an event with optional arguments */
111
publishEvent: (name: string, ...args: any[]) => void;
112
113
/** Display error overlay component */
114
showError: (props: any) => void;
115
}
116
```
117
118
**Usage Examples:**
119
120
```typescript
121
function CoreApiExamples() {
122
const apiRef = useApiRef();
123
124
const handleResize = () => {
125
// Force grid to recalculate after container size change
126
if (apiRef.current) {
127
apiRef.current.resize();
128
}
129
};
130
131
const showCustomError = () => {
132
if (apiRef.current) {
133
apiRef.current.showError({
134
message: "Custom error message",
135
details: "Additional error details"
136
});
137
}
138
};
139
140
const checkGridState = () => {
141
if (apiRef.current) {
142
const isReady = apiRef.current.isInitialized();
143
const rootElement = apiRef.current.getRootElement();
144
console.log("Grid ready:", isReady);
145
console.log("Root element:", rootElement);
146
}
147
};
148
149
// Listen for window resize and update grid
150
React.useEffect(() => {
151
window.addEventListener('resize', handleResize);
152
return () => window.removeEventListener('resize', handleResize);
153
}, []);
154
155
return (
156
<div>
157
<button onClick={showCustomError}>Show Error</button>
158
<button onClick={checkGridState}>Check State</button>
159
<DataGrid apiRef={apiRef} rows={rows} columns={columns} />
160
</div>
161
);
162
}
163
```
164
165
### Events API
166
167
Event subscription and management system for grid events.
168
169
```typescript { .api }
170
/**
171
* Event system API for subscribing to and managing grid events
172
* Provides fine-grained control over event handling
173
*/
174
interface EventsApi {
175
/** Subscribe to a specific grid event */
176
subscribeEvent(event: string, handler: (...args: any[]) => void): () => void;
177
178
/** Publish/emit a custom event */
179
publishEvent(event: string, ...args: any[]): void;
180
181
/** Remove all event listeners */
182
removeAllListeners(): void;
183
}
184
```
185
186
**Usage Examples:**
187
188
```typescript
189
function EventsApiExamples() {
190
const apiRef = useApiRef();
191
192
React.useEffect(() => {
193
if (!apiRef.current) return;
194
195
// Subscribe to cell click events
196
const unsubscribeCellClick = apiRef.current.subscribeEvent(
197
'cellClick',
198
(params) => {
199
console.log('Cell clicked via API:', params);
200
}
201
);
202
203
// Subscribe to selection change events
204
const unsubscribeSelection = apiRef.current.subscribeEvent(
205
'selectionChange',
206
(params) => {
207
console.log('Selection changed via API:', params);
208
}
209
);
210
211
// Cleanup subscriptions
212
return () => {
213
unsubscribeCellClick();
214
unsubscribeSelection();
215
};
216
}, []);
217
218
const publishCustomEvent = () => {
219
if (apiRef.current) {
220
apiRef.current.publishEvent('customEvent', {
221
message: 'Custom event data',
222
timestamp: Date.now()
223
});
224
}
225
};
226
227
return (
228
<div>
229
<button onClick={publishCustomEvent}>Publish Custom Event</button>
230
<DataGrid apiRef={apiRef} rows={rows} columns={columns} />
231
</div>
232
);
233
}
234
```
235
236
### Row API
237
238
Methods for programmatic row management and data manipulation.
239
240
```typescript { .api }
241
/**
242
* Row management API for programmatic row operations
243
* Provides access to row data, state, and manipulation methods
244
*/
245
interface RowApi {
246
/** Get all row models as Rows array */
247
getRowModels(): Rows;
248
249
/** Get current row count */
250
getRowsCount(): number;
251
252
/** Get all row IDs */
253
getAllRowIds(): RowId[];
254
255
/** Set new set of row models */
256
setRowModels(rows: Rows): void;
257
258
/** Update row model properties */
259
updateRowModels(updates: Partial<RowModel>[]): void;
260
261
/** Update row data */
262
updateRowData(updates: RowData[]): void;
263
264
/** Get row ID by index */
265
getRowIdFromRowIndex(index: number): RowId;
266
267
/** Get row index by ID */
268
getRowIndexFromId(id: RowId): number;
269
270
/** Get row model by ID */
271
getRowFromId(id: RowId): RowModel;
272
}
273
274
interface RowUpdate {
275
id: RowId;
276
[field: string]: any;
277
}
278
```
279
280
**Usage Examples:**
281
282
```typescript
283
function RowApiExamples() {
284
const apiRef = useApiRef();
285
286
const getRowInfo = () => {
287
if (!apiRef.current) return;
288
289
const totalRows = apiRef.current.getRowsCount();
290
const allIds = apiRef.current.getAllRowIds();
291
const firstRow = apiRef.current.getRow(allIds[0]);
292
293
console.log("Total rows:", totalRows);
294
console.log("First row data:", firstRow);
295
};
296
297
const updateRowData = () => {
298
if (!apiRef.current || rows.length === 0) return;
299
300
const updates = [
301
{
302
id: rows[0].id,
303
name: "Updated Name",
304
lastModified: new Date().toISOString()
305
}
306
];
307
308
apiRef.current.updateRows(updates);
309
};
310
311
const findRowIndex = () => {
312
if (!apiRef.current || rows.length === 0) return;
313
314
const firstRowId = rows[0].id;
315
const index = apiRef.current.getRowIndex(firstRowId);
316
console.log(`Row ${firstRowId} is at index ${index}`);
317
};
318
319
return (
320
<div>
321
<button onClick={getRowInfo}>Get Row Info</button>
322
<button onClick={updateRowData}>Update First Row</button>
323
<button onClick={findRowIndex}>Find Row Index</button>
324
<DataGrid apiRef={apiRef} rows={rows} columns={columns} />
325
</div>
326
);
327
}
328
```
329
330
### Column API
331
332
Methods for programmatic column management and configuration.
333
334
```typescript { .api }
335
/**
336
* Column management API for programmatic column operations
337
* Provides access to column definitions, visibility, and sizing
338
*/
339
interface ColumnApi {
340
/** Retrieve a column from its field */
341
getColumnFromField: (field: string) => ColDef;
342
343
/** Get all the columns */
344
getAllColumns: () => Columns;
345
346
/** Get the currently visible columns */
347
getVisibleColumns: () => Columns;
348
349
/** Get the columns meta data */
350
getColumnsMeta: () => ColumnsMeta;
351
352
/** Get the index position of the column in the array of ColDef */
353
getColumnIndex: (field: string) => number;
354
355
/** Get the column left position in pixel relative to the left grid inner border */
356
getColumnPosition: (field: string) => number;
357
358
/** Allows to update a column ColDef model */
359
updateColumn: (col: ColDef) => void;
360
361
/** Allows to batch update multiple columns at the same time */
362
updateColumns: (cols: ColDef[]) => void;
363
}
364
```
365
366
**Usage Examples:**
367
368
```typescript
369
function ColumnApiExamples() {
370
const apiRef = useApiRef();
371
372
const getColumnInfo = () => {
373
if (!apiRef.current) return;
374
375
const allColumns = apiRef.current.getAllColumns();
376
const visibleColumns = apiRef.current.getVisibleColumns();
377
const nameColumn = apiRef.current.getColumn('name');
378
379
console.log("Total columns:", allColumns.length);
380
console.log("Visible columns:", visibleColumns.length);
381
console.log("Name column:", nameColumn);
382
};
383
384
const toggleColumnVisibility = (field: string) => {
385
if (!apiRef.current) return;
386
387
const column = apiRef.current.getColumn(field);
388
if (column) {
389
const isVisible = !column.hide;
390
apiRef.current.setColumnVisibility(field, !isVisible);
391
}
392
};
393
394
const resizeColumn = (field: string, width: number) => {
395
if (!apiRef.current) return;
396
397
apiRef.current.setColumnWidth(field, width);
398
};
399
400
return (
401
<div>
402
<button onClick={getColumnInfo}>Get Column Info</button>
403
<button onClick={() => toggleColumnVisibility('age')}>
404
Toggle Age Column
405
</button>
406
<button onClick={() => resizeColumn('name', 200)}>
407
Resize Name Column
408
</button>
409
<DataGrid apiRef={apiRef} rows={rows} columns={columns} />
410
</div>
411
);
412
}
413
```
414
415
### Selection API
416
417
Methods for programmatic row selection management.
418
419
```typescript { .api }
420
/**
421
* Selection management API for programmatic selection control
422
* Community edition supports single row selection only
423
*/
424
interface SelectionApi {
425
/** Toggle row selected state */
426
selectRow(id: RowId, allowMultiple?: boolean, isSelected?: boolean): void;
427
428
/** Batch toggle rows selected state */
429
selectRows(ids: RowId[], isSelected?: boolean, deselectOtherRows?: boolean): void;
430
431
/** Get array of selected row models */
432
getSelectedRows(): RowModel[];
433
434
/** Register handler for row selection events */
435
onRowSelected(handler: (params: RowSelectedParams) => void): () => void;
436
437
/** Register handler for selection change events */
438
onSelectionChange(handler: (params: SelectionChangeParams) => void): () => void;
439
}
440
```
441
442
**Usage Examples:**
443
444
```typescript
445
function SelectionApiExamples() {
446
const apiRef = useApiRef();
447
const [selectedCount, setSelectedCount] = React.useState(0);
448
449
const selectFirstRow = () => {
450
if (!apiRef.current || rows.length === 0) return;
451
452
apiRef.current.selectRow(rows[0].id, true);
453
};
454
455
const clearSelection = () => {
456
if (!apiRef.current) return;
457
458
apiRef.current.deselectAll();
459
};
460
461
const getSelectionInfo = () => {
462
if (!apiRef.current) return;
463
464
const selected = apiRef.current.getSelectedRows();
465
const isFirstSelected = rows.length > 0 && apiRef.current.isRowSelected(rows[0].id);
466
467
console.log("Selected rows:", selected);
468
console.log("First row selected:", isFirstSelected);
469
setSelectedCount(selected.length);
470
};
471
472
return (
473
<div>
474
<button onClick={selectFirstRow}>Select First Row</button>
475
<button onClick={clearSelection}>Clear Selection</button>
476
<button onClick={getSelectionInfo}>Get Selection Info</button>
477
<div>Selected: {selectedCount} rows</div>
478
<DataGrid
479
apiRef={apiRef}
480
rows={rows}
481
columns={columns}
482
checkboxSelection
483
/>
484
</div>
485
);
486
}
487
```
488
489
### Sort API
490
491
Methods for programmatic sorting control and state management.
492
493
```typescript { .api }
494
/**
495
* Sorting API for programmatic sort control
496
* Community edition supports single column sorting only
497
*/
498
interface SortApi {
499
/** Get current sort model */
500
getSortModel(): SortModel[];
501
502
/** Set sort model */
503
setSortModel(model: SortModel[]): void;
504
505
/** Sort by specific column */
506
sortColumn(field: string, direction: SortDirection): void;
507
508
/** Clear all sorting */
509
clearSort(): void;
510
511
/** Get sorted row IDs in current order */
512
getSortedRowIds(): RowId[];
513
}
514
```
515
516
**Usage Examples:**
517
518
```typescript
519
function SortApiExamples() {
520
const apiRef = useApiRef();
521
const [currentSort, setCurrentSort] = React.useState<SortModel[]>([]);
522
523
const sortByName = (direction: SortDirection) => {
524
if (!apiRef.current) return;
525
526
apiRef.current.sortColumn('name', direction);
527
};
528
529
const clearAllSort = () => {
530
if (!apiRef.current) return;
531
532
apiRef.current.clearSort();
533
};
534
535
const getSortInfo = () => {
536
if (!apiRef.current) return;
537
538
const sortModel = apiRef.current.getSortModel();
539
const sortedIds = apiRef.current.getSortedRowIds();
540
541
setCurrentSort(sortModel);
542
console.log("Current sort:", sortModel);
543
console.log("Sorted row IDs:", sortedIds);
544
};
545
546
return (
547
<div>
548
<button onClick={() => sortByName('asc')}>Sort Name A-Z</button>
549
<button onClick={() => sortByName('desc')}>Sort Name Z-A</button>
550
<button onClick={clearAllSort}>Clear Sort</button>
551
<button onClick={getSortInfo}>Get Sort Info</button>
552
<div>
553
Current sort: {currentSort.length > 0
554
? `${currentSort[0].field} ${currentSort[0].sort}`
555
: 'None'}
556
</div>
557
<DataGrid apiRef={apiRef} rows={rows} columns={columns} />
558
</div>
559
);
560
}
561
```
562
563
### Pagination API
564
565
Methods for programmatic pagination control and state management.
566
567
```typescript { .api }
568
/**
569
* Pagination API for programmatic pagination control
570
* Provides access to page state and navigation methods
571
*/
572
interface PaginationApi {
573
/** Set the displayed page */
574
setPage: (page: number) => void;
575
576
/** Set the number of rows in one page */
577
setPageSize: (pageSize: number) => void;
578
579
/** Handler that is triggered after a new page has been displayed */
580
onPageChange: (handler: (param: PageChangeParams) => void) => () => void;
581
582
/** Handler that is triggered after the page size was changed */
583
onPageSizeChange: (handler: (param: PageChangeParams) => void) => () => void;
584
}
585
```
586
587
**Usage Examples:**
588
589
```typescript
590
function PaginationApiExamples() {
591
const apiRef = useApiRef();
592
const [pageInfo, setPageInfo] = React.useState({ page: 1, pageSize: 25, pageCount: 1 });
593
594
const updatePageInfo = () => {
595
if (!apiRef.current) return;
596
597
const page = apiRef.current.getPage();
598
const pageSize = apiRef.current.getPageSize();
599
const pageCount = apiRef.current.getPageCount();
600
601
setPageInfo({ page, pageSize, pageCount });
602
};
603
604
const navigatePages = (action: string) => {
605
if (!apiRef.current) return;
606
607
switch (action) {
608
case 'first':
609
apiRef.current.goToFirstPage();
610
break;
611
case 'prev':
612
apiRef.current.goToPreviousPage();
613
break;
614
case 'next':
615
apiRef.current.goToNextPage();
616
break;
617
case 'last':
618
apiRef.current.goToLastPage();
619
break;
620
}
621
622
// Update info after navigation
623
setTimeout(updatePageInfo, 100);
624
};
625
626
const changePageSize = (newSize: number) => {
627
if (!apiRef.current) return;
628
629
// Check community edition limit
630
const size = Math.min(newSize, 100);
631
apiRef.current.setPageSize(size);
632
633
setTimeout(updatePageInfo, 100);
634
};
635
636
return (
637
<div>
638
<div style={{ marginBottom: '10px' }}>
639
<button onClick={() => navigatePages('first')}>First</button>
640
<button onClick={() => navigatePages('prev')}>Previous</button>
641
<button onClick={() => navigatePages('next')}>Next</button>
642
<button onClick={() => navigatePages('last')}>Last</button>
643
</div>
644
<div style={{ marginBottom: '10px' }}>
645
<button onClick={() => changePageSize(10)}>10 per page</button>
646
<button onClick={() => changePageSize(25)}>25 per page</button>
647
<button onClick={() => changePageSize(50)}>50 per page</button>
648
<button onClick={updatePageInfo}>Refresh Info</button>
649
</div>
650
<div>
651
Page {pageInfo.page} of {pageInfo.pageCount}
652
(showing {pageInfo.pageSize} per page)
653
</div>
654
<DataGrid
655
apiRef={apiRef}
656
rows={rows}
657
columns={columns}
658
pagination={true}
659
pageSize={25}
660
/>
661
</div>
662
);
663
}
664
```
665
666
### Virtualization API
667
668
Methods for controlling virtual scrolling and viewport management.
669
670
```typescript { .api }
671
/**
672
* Virtualization API for scroll and viewport control
673
* Manages virtual rendering for performance with large datasets
674
*/
675
interface VirtualizationApi {
676
/** Scroll to specific row and column indexes */
677
scrollToIndexes(params: { rowIndex?: number; colIndex?: number }): void;
678
679
/** Get current scroll position */
680
getScrollPosition(): { top: number; left: number };
681
682
/** Set scroll position */
683
setScrollPosition(position: { top?: number; left?: number }): void;
684
685
/** Get currently visible row range */
686
getVisibleRowRange(): { firstRowIndex: number; lastRowIndex: number };
687
688
/** Get currently visible column range */
689
getVisibleColumnRange(): { firstColIndex: number; lastColIndex: number };
690
}
691
```
692
693
**Usage Examples:**
694
695
```typescript
696
function VirtualizationApiExamples() {
697
const apiRef = useApiRef();
698
699
const scrollToTop = () => {
700
if (!apiRef.current) return;
701
702
apiRef.current.scrollToIndexes({ rowIndex: 0, colIndex: 0 });
703
};
704
705
const scrollToRow = (rowIndex: number) => {
706
if (!apiRef.current) return;
707
708
apiRef.current.scrollToIndexes({ rowIndex });
709
};
710
711
const getViewportInfo = () => {
712
if (!apiRef.current) return;
713
714
const scrollPos = apiRef.current.getScrollPosition();
715
const visibleRows = apiRef.current.getVisibleRowRange();
716
const visibleCols = apiRef.current.getVisibleColumnRange();
717
718
console.log("Scroll position:", scrollPos);
719
console.log("Visible rows:", visibleRows);
720
console.log("Visible columns:", visibleCols);
721
};
722
723
const scrollToBottom = () => {
724
if (!apiRef.current) return;
725
726
const lastRowIndex = rows.length - 1;
727
apiRef.current.scrollToIndexes({ rowIndex: lastRowIndex });
728
};
729
730
return (
731
<div>
732
<button onClick={scrollToTop}>Scroll to Top</button>
733
<button onClick={() => scrollToRow(50)}>Scroll to Row 50</button>
734
<button onClick={scrollToBottom}>Scroll to Bottom</button>
735
<button onClick={getViewportInfo}>Get Viewport Info</button>
736
<DataGrid
737
apiRef={apiRef}
738
rows={rows}
739
columns={columns}
740
style={{ height: 400 }}
741
/>
742
</div>
743
);
744
}
745
```