CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-material-ui--data-grid

Community edition React data grid component with sorting, filtering, pagination, and Material-UI integration

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

api-reference.mddocs/

API Reference

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.

Capabilities

API Reference Hook

Hook for creating and managing grid API references for imperative control.

/**
 * Creates an API reference for programmatic grid control
 * The returned ref can be passed to the DataGrid component
 * @returns ApiRef object for accessing grid methods and state
 */
function useApiRef(): ApiRef;

/**
 * API reference type - mutable ref containing the grid API
 * Provides access to all grid methods and event subscription
 */
type ApiRef = React.MutableRefObject<GridApi>;

Usage Examples:

import React from "react";
import { DataGrid, useApiRef } from "@material-ui/data-grid";

function ApiControlledGrid() {
  const apiRef = useApiRef();

  const selectFirstRow = () => {
    if (apiRef.current && rows.length > 0) {
      apiRef.current.selectRow(rows[0].id);
    }
  };

  const clearSelection = () => {
    if (apiRef.current) {
      apiRef.current.selectRows([]);
    }
  };

  const scrollToTop = () => {
    if (apiRef.current) {
      apiRef.current.scrollToIndexes({ rowIndex: 0, colIndex: 0 });
    }
  };

  return (
    <div>
      <div style={{ marginBottom: "10px" }}>
        <button onClick={selectFirstRow}>Select First Row</button>
        <button onClick={clearSelection}>Clear Selection</button>
        <button onClick={scrollToTop}>Scroll to Top</button>
      </div>
      <div style={{ height: 600, width: "100%" }}>
        <DataGrid
          apiRef={apiRef}
          rows={rows}
          columns={columns}
          checkboxSelection
        />
      </div>
    </div>
  );
}

Grid API Interface

Complete API interface providing access to all grid functionality and state.

/**
 * Complete Grid API interface combining all sub-APIs
 * Provides comprehensive programmatic control over grid behavior
 */
interface GridApi extends 
  CoreApi, 
  EventsApi, 
  RowApi, 
  ColumnApi, 
  SelectionApi, 
  SortApi, 
  VirtualizationApi, 
  PaginationApi {
  // Combined interface with all grid capabilities
}

Core API

Essential grid methods for basic functionality and state management.

/**
 * Core API methods for basic grid operations
 * Includes initialization, error handling, and general utilities
 */
interface CoreApi extends EventEmitter {
  /** Property indicating if grid EventEmitter is initialized */
  isInitialised: boolean;
  
  /** Register event handler and return unsubscribe function */
  subscribeEvent: (event: string, handler: (param: any) => void) => () => void;
  
  /** Emit an event with optional arguments */
  publishEvent: (name: string, ...args: any[]) => void;
  
  /** Display error overlay component */
  showError: (props: any) => void;
}

Usage Examples:

function CoreApiExamples() {
  const apiRef = useApiRef();

  const handleResize = () => {
    // Force grid to recalculate after container size change
    if (apiRef.current) {
      apiRef.current.resize();
    }
  };

  const showCustomError = () => {
    if (apiRef.current) {
      apiRef.current.showError({
        message: "Custom error message",
        details: "Additional error details"
      });
    }
  };

  const checkGridState = () => {
    if (apiRef.current) {
      const isReady = apiRef.current.isInitialized();
      const rootElement = apiRef.current.getRootElement();
      console.log("Grid ready:", isReady);
      console.log("Root element:", rootElement);
    }
  };

  // Listen for window resize and update grid
  React.useEffect(() => {
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return (
    <div>
      <button onClick={showCustomError}>Show Error</button>
      <button onClick={checkGridState}>Check State</button>
      <DataGrid apiRef={apiRef} rows={rows} columns={columns} />
    </div>
  );
}

Events API

Event subscription and management system for grid events.

/**
 * Event system API for subscribing to and managing grid events
 * Provides fine-grained control over event handling
 */
interface EventsApi {
  /** Subscribe to a specific grid event */
  subscribeEvent(event: string, handler: (...args: any[]) => void): () => void;
  
  /** Publish/emit a custom event */
  publishEvent(event: string, ...args: any[]): void;
  
  /** Remove all event listeners */
  removeAllListeners(): void;
}

Usage Examples:

function EventsApiExamples() {
  const apiRef = useApiRef();

  React.useEffect(() => {
    if (!apiRef.current) return;

    // Subscribe to cell click events
    const unsubscribeCellClick = apiRef.current.subscribeEvent(
      'cellClick',
      (params) => {
        console.log('Cell clicked via API:', params);
      }
    );

    // Subscribe to selection change events
    const unsubscribeSelection = apiRef.current.subscribeEvent(
      'selectionChange',
      (params) => {
        console.log('Selection changed via API:', params);
      }
    );

    // Cleanup subscriptions
    return () => {
      unsubscribeCellClick();
      unsubscribeSelection();
    };
  }, []);

  const publishCustomEvent = () => {
    if (apiRef.current) {
      apiRef.current.publishEvent('customEvent', {
        message: 'Custom event data',
        timestamp: Date.now()
      });
    }
  };

  return (
    <div>
      <button onClick={publishCustomEvent}>Publish Custom Event</button>
      <DataGrid apiRef={apiRef} rows={rows} columns={columns} />
    </div>
  );
}

Row API

Methods for programmatic row management and data manipulation.

/**
 * Row management API for programmatic row operations
 * Provides access to row data, state, and manipulation methods
 */
interface RowApi {
  /** Get all row models as Rows array */
  getRowModels(): Rows;
  
  /** Get current row count */
  getRowsCount(): number;
  
  /** Get all row IDs */
  getAllRowIds(): RowId[];
  
  /** Set new set of row models */
  setRowModels(rows: Rows): void;
  
  /** Update row model properties */
  updateRowModels(updates: Partial<RowModel>[]): void;
  
  /** Update row data */
  updateRowData(updates: RowData[]): void;
  
  /** Get row ID by index */
  getRowIdFromRowIndex(index: number): RowId;
  
  /** Get row index by ID */
  getRowIndexFromId(id: RowId): number;
  
  /** Get row model by ID */
  getRowFromId(id: RowId): RowModel;
}

interface RowUpdate {
  id: RowId;
  [field: string]: any;
}

Usage Examples:

function RowApiExamples() {
  const apiRef = useApiRef();

  const getRowInfo = () => {
    if (!apiRef.current) return;

    const totalRows = apiRef.current.getRowsCount();
    const allIds = apiRef.current.getAllRowIds();
    const firstRow = apiRef.current.getRow(allIds[0]);
    
    console.log("Total rows:", totalRows);
    console.log("First row data:", firstRow);
  };

  const updateRowData = () => {
    if (!apiRef.current || rows.length === 0) return;

    const updates = [
      {
        id: rows[0].id,
        name: "Updated Name",
        lastModified: new Date().toISOString()
      }
    ];

    apiRef.current.updateRows(updates);
  };

  const findRowIndex = () => {
    if (!apiRef.current || rows.length === 0) return;

    const firstRowId = rows[0].id;
    const index = apiRef.current.getRowIndex(firstRowId);
    console.log(`Row ${firstRowId} is at index ${index}`);
  };

  return (
    <div>
      <button onClick={getRowInfo}>Get Row Info</button>
      <button onClick={updateRowData}>Update First Row</button>
      <button onClick={findRowIndex}>Find Row Index</button>
      <DataGrid apiRef={apiRef} rows={rows} columns={columns} />
    </div>
  );
}

Column API

Methods for programmatic column management and configuration.

/**
 * Column management API for programmatic column operations
 * Provides access to column definitions, visibility, and sizing
 */
interface ColumnApi {
  /** Retrieve a column from its field */
  getColumnFromField: (field: string) => ColDef;
  
  /** Get all the columns */
  getAllColumns: () => Columns;
  
  /** Get the currently visible columns */
  getVisibleColumns: () => Columns;
  
  /** Get the columns meta data */
  getColumnsMeta: () => ColumnsMeta;
  
  /** Get the index position of the column in the array of ColDef */
  getColumnIndex: (field: string) => number;
  
  /** Get the column left position in pixel relative to the left grid inner border */
  getColumnPosition: (field: string) => number;
  
  /** Allows to update a column ColDef model */
  updateColumn: (col: ColDef) => void;
  
  /** Allows to batch update multiple columns at the same time */
  updateColumns: (cols: ColDef[]) => void;
}

Usage Examples:

function ColumnApiExamples() {
  const apiRef = useApiRef();

  const getColumnInfo = () => {
    if (!apiRef.current) return;

    const allColumns = apiRef.current.getAllColumns();
    const visibleColumns = apiRef.current.getVisibleColumns();
    const nameColumn = apiRef.current.getColumn('name');
    
    console.log("Total columns:", allColumns.length);
    console.log("Visible columns:", visibleColumns.length);
    console.log("Name column:", nameColumn);
  };

  const toggleColumnVisibility = (field: string) => {
    if (!apiRef.current) return;

    const column = apiRef.current.getColumn(field);
    if (column) {
      const isVisible = !column.hide;
      apiRef.current.setColumnVisibility(field, !isVisible);
    }
  };

  const resizeColumn = (field: string, width: number) => {
    if (!apiRef.current) return;

    apiRef.current.setColumnWidth(field, width);
  };

  return (
    <div>
      <button onClick={getColumnInfo}>Get Column Info</button>
      <button onClick={() => toggleColumnVisibility('age')}>
        Toggle Age Column
      </button>
      <button onClick={() => resizeColumn('name', 200)}>
        Resize Name Column
      </button>
      <DataGrid apiRef={apiRef} rows={rows} columns={columns} />
    </div>
  );
}

Selection API

Methods for programmatic row selection management.

/**
 * Selection management API for programmatic selection control
 * Community edition supports single row selection only
 */
interface SelectionApi {
  /** Toggle row selected state */
  selectRow(id: RowId, allowMultiple?: boolean, isSelected?: boolean): void;
  
  /** Batch toggle rows selected state */
  selectRows(ids: RowId[], isSelected?: boolean, deselectOtherRows?: boolean): void;
  
  /** Get array of selected row models */
  getSelectedRows(): RowModel[];
  
  /** Register handler for row selection events */
  onRowSelected(handler: (params: RowSelectedParams) => void): () => void;
  
  /** Register handler for selection change events */
  onSelectionChange(handler: (params: SelectionChangeParams) => void): () => void;
}

Usage Examples:

function SelectionApiExamples() {
  const apiRef = useApiRef();
  const [selectedCount, setSelectedCount] = React.useState(0);

  const selectFirstRow = () => {
    if (!apiRef.current || rows.length === 0) return;

    apiRef.current.selectRow(rows[0].id, true);
  };

  const clearSelection = () => {
    if (!apiRef.current) return;

    apiRef.current.deselectAll();
  };

  const getSelectionInfo = () => {
    if (!apiRef.current) return;

    const selected = apiRef.current.getSelectedRows();
    const isFirstSelected = rows.length > 0 && apiRef.current.isRowSelected(rows[0].id);
    
    console.log("Selected rows:", selected);
    console.log("First row selected:", isFirstSelected);
    setSelectedCount(selected.length);
  };

  return (
    <div>
      <button onClick={selectFirstRow}>Select First Row</button>
      <button onClick={clearSelection}>Clear Selection</button>
      <button onClick={getSelectionInfo}>Get Selection Info</button>
      <div>Selected: {selectedCount} rows</div>
      <DataGrid 
        apiRef={apiRef} 
        rows={rows} 
        columns={columns} 
        checkboxSelection 
      />
    </div>
  );
}

Sort API

Methods for programmatic sorting control and state management.

/**
 * Sorting API for programmatic sort control
 * Community edition supports single column sorting only
 */
interface SortApi {
  /** Get current sort model */
  getSortModel(): SortModel[];
  
  /** Set sort model */
  setSortModel(model: SortModel[]): void;
  
  /** Sort by specific column */
  sortColumn(field: string, direction: SortDirection): void;
  
  /** Clear all sorting */
  clearSort(): void;
  
  /** Get sorted row IDs in current order */
  getSortedRowIds(): RowId[];
}

Usage Examples:

function SortApiExamples() {
  const apiRef = useApiRef();
  const [currentSort, setCurrentSort] = React.useState<SortModel[]>([]);

  const sortByName = (direction: SortDirection) => {
    if (!apiRef.current) return;

    apiRef.current.sortColumn('name', direction);
  };

  const clearAllSort = () => {
    if (!apiRef.current) return;

    apiRef.current.clearSort();
  };

  const getSortInfo = () => {
    if (!apiRef.current) return;

    const sortModel = apiRef.current.getSortModel();
    const sortedIds = apiRef.current.getSortedRowIds();
    
    setCurrentSort(sortModel);
    console.log("Current sort:", sortModel);
    console.log("Sorted row IDs:", sortedIds);
  };

  return (
    <div>
      <button onClick={() => sortByName('asc')}>Sort Name A-Z</button>
      <button onClick={() => sortByName('desc')}>Sort Name Z-A</button>
      <button onClick={clearAllSort}>Clear Sort</button>
      <button onClick={getSortInfo}>Get Sort Info</button>
      <div>
        Current sort: {currentSort.length > 0 
          ? `${currentSort[0].field} ${currentSort[0].sort}` 
          : 'None'}
      </div>
      <DataGrid apiRef={apiRef} rows={rows} columns={columns} />
    </div>
  );
}

Pagination API

Methods for programmatic pagination control and state management.

/**
 * Pagination API for programmatic pagination control
 * Provides access to page state and navigation methods
 */
interface PaginationApi {
  /** Set the displayed page */
  setPage: (page: number) => void;
  
  /** Set the number of rows in one page */
  setPageSize: (pageSize: number) => void;
  
  /** Handler that is triggered after a new page has been displayed */
  onPageChange: (handler: (param: PageChangeParams) => void) => () => void;
  
  /** Handler that is triggered after the page size was changed */
  onPageSizeChange: (handler: (param: PageChangeParams) => void) => () => void;
}

Usage Examples:

function PaginationApiExamples() {
  const apiRef = useApiRef();
  const [pageInfo, setPageInfo] = React.useState({ page: 1, pageSize: 25, pageCount: 1 });

  const updatePageInfo = () => {
    if (!apiRef.current) return;

    const page = apiRef.current.getPage();
    const pageSize = apiRef.current.getPageSize();
    const pageCount = apiRef.current.getPageCount();
    
    setPageInfo({ page, pageSize, pageCount });
  };

  const navigatePages = (action: string) => {
    if (!apiRef.current) return;

    switch (action) {
      case 'first':
        apiRef.current.goToFirstPage();
        break;
      case 'prev':
        apiRef.current.goToPreviousPage();
        break;
      case 'next':
        apiRef.current.goToNextPage();
        break;
      case 'last':
        apiRef.current.goToLastPage();
        break;
    }
    
    // Update info after navigation
    setTimeout(updatePageInfo, 100);
  };

  const changePageSize = (newSize: number) => {
    if (!apiRef.current) return;

    // Check community edition limit
    const size = Math.min(newSize, 100);
    apiRef.current.setPageSize(size);
    
    setTimeout(updatePageInfo, 100);
  };

  return (
    <div>
      <div style={{ marginBottom: '10px' }}>
        <button onClick={() => navigatePages('first')}>First</button>
        <button onClick={() => navigatePages('prev')}>Previous</button>
        <button onClick={() => navigatePages('next')}>Next</button>
        <button onClick={() => navigatePages('last')}>Last</button>
      </div>
      <div style={{ marginBottom: '10px' }}>
        <button onClick={() => changePageSize(10)}>10 per page</button>
        <button onClick={() => changePageSize(25)}>25 per page</button>
        <button onClick={() => changePageSize(50)}>50 per page</button>
        <button onClick={updatePageInfo}>Refresh Info</button>
      </div>
      <div>
        Page {pageInfo.page} of {pageInfo.pageCount} 
        (showing {pageInfo.pageSize} per page)
      </div>
      <DataGrid 
        apiRef={apiRef} 
        rows={rows} 
        columns={columns} 
        pagination={true}
        pageSize={25}
      />
    </div>
  );
}

Virtualization API

Methods for controlling virtual scrolling and viewport management.

/**
 * Virtualization API for scroll and viewport control
 * Manages virtual rendering for performance with large datasets
 */
interface VirtualizationApi {
  /** Scroll to specific row and column indexes */
  scrollToIndexes(params: { rowIndex?: number; colIndex?: number }): void;
  
  /** Get current scroll position */
  getScrollPosition(): { top: number; left: number };
  
  /** Set scroll position */
  setScrollPosition(position: { top?: number; left?: number }): void;
  
  /** Get currently visible row range */
  getVisibleRowRange(): { firstRowIndex: number; lastRowIndex: number };
  
  /** Get currently visible column range */
  getVisibleColumnRange(): { firstColIndex: number; lastColIndex: number };
}

Usage Examples:

function VirtualizationApiExamples() {
  const apiRef = useApiRef();

  const scrollToTop = () => {
    if (!apiRef.current) return;

    apiRef.current.scrollToIndexes({ rowIndex: 0, colIndex: 0 });
  };

  const scrollToRow = (rowIndex: number) => {
    if (!apiRef.current) return;

    apiRef.current.scrollToIndexes({ rowIndex });
  };

  const getViewportInfo = () => {
    if (!apiRef.current) return;

    const scrollPos = apiRef.current.getScrollPosition();
    const visibleRows = apiRef.current.getVisibleRowRange();
    const visibleCols = apiRef.current.getVisibleColumnRange();
    
    console.log("Scroll position:", scrollPos);
    console.log("Visible rows:", visibleRows);
    console.log("Visible columns:", visibleCols);
  };

  const scrollToBottom = () => {
    if (!apiRef.current) return;

    const lastRowIndex = rows.length - 1;
    apiRef.current.scrollToIndexes({ rowIndex: lastRowIndex });
  };

  return (
    <div>
      <button onClick={scrollToTop}>Scroll to Top</button>
      <button onClick={() => scrollToRow(50)}>Scroll to Row 50</button>
      <button onClick={scrollToBottom}>Scroll to Bottom</button>
      <button onClick={getViewportInfo}>Get Viewport Info</button>
      <DataGrid 
        apiRef={apiRef} 
        rows={rows} 
        columns={columns} 
        style={{ height: 400 }}
      />
    </div>
  );
}

docs

api-reference.md

column-system.md

configuration-options.md

data-grid-component.md

event-handling.md

index.md

row-management.md

tile.json