# DataTable

DataTable is a table component that displays structured data and provides various interactions such as sorting, selection, editing, and pagination.
The examples below can be tested in the story canvas, and the displayed code can be reused as-is.

## Basic Usage

```tsx
<DataTable
  onPaginationModelChange={fn()}
  onSelectionModelChange={fn()}
  onRowClick={fn()}
  columns={[{
  field: 'dessert',
  headerName: 'Dessert (100g serving)',
  width: '40%'
}, {
  field: 'calories',
  headerName: 'Calories',
  type: 'number'
}, {
  field: 'fat',
  headerName: 'Fat (g)',
  type: 'number'
}, {
  field: 'carbs',
  headerName: 'Carbs (g)',
  type: 'number'
}, {
  field: 'protein',
  headerName: 'Protein (g)',
  type: 'number'
}]}
  rows={rows}
/>
```

| Field    | Description | Default |
| -------- | ----------- | ------- |
| editMode | —           | false   |

### Required Data Structure

- `rows` is an array, and by default, each row must include an `id` field.
- If there is no `id`, you can specify a row identifier using `getId`.

```tsx
<DataTable
  rows={rows}
  columns={columns}
/>

<DataTable
  rows={rows}
  columns={columns}
  getId={(row) => row.uuid}
/>
```

## Column Definition (ColumnDef)

### Basic Options

```tsx
const columns = [
  {
    field: 'name',
    headerName: 'Name',
    width: '30%',
    minWidth: '120px',
    maxWidth: '320px',
    sortable: true,
    description: 'Description displayed as a tooltip',
    headerClassName: 'table-head',
    cellClassName: ({ row }) => (row.isHot ? 'cell-hot' : undefined),
  },
];
```

### Column Types

DataTable supports various column types. Each type provides an appropriate input UI in edit mode.

#### text (default)

The default text type. If `type` is not specified, it defaults to text.

```tsx
{
  field: 'name',
  headerName: 'Name',
  type: 'text', // can be omitted
}
```

#### number

A type for numeric input.

```tsx
{
  field: 'quantity',
  headerName: 'Quantity',
  type: 'number',
}
```

#### currency

A type for currency input. Uses the `CurrencyInput` component.

```tsx
<DataTable rows={tableRows} columns={columns} editMode noWrap />
```

```tsx
{
  field: 'price',
  headerName: 'Price',
  type: 'currency',
  componentProps: {
    currencyDisplay: 'narrowSymbol',
    currency: 'USD',
  },
}
```

#### date

A type for date selection. Uses the `DatePicker` component.

```tsx
<DataTable rows={tableRows} columns={columns} editMode noWrap />
```

```tsx
{
  field: 'dueDate',
  headerName: 'Due Date',
  type: 'date',
  componentProps: {
    format: 'yyyy-MM-dd',
  },
}
```

#### select

A type for dropdown selection. Uses the `Select` component.

```tsx
<DataTable rows={tableRows} columns={columns} editMode noWrap />
```

```tsx
{
  field: 'status',
  headerName: 'Status',
  type: 'select',
  componentProps: {
    options: ['Pending', 'In Progress', 'Completed', 'Cancelled'],
  },
}
```

#### autocomplete

A type for autocomplete selection. Uses the `Autocomplete` component.

```tsx
<DataTable rows={tableRows} columns={columns} editMode noWrap />
```

```tsx
{
  field: 'assignee',
  headerName: 'Assignee',
  type: 'autocomplete',
  componentProps: {
    options: ['Alice', 'Bob', 'Charlie', 'Diana'],
    placeholder: 'Select assignee...',
  },
}
```

#### longText

A type for long text input. Uses the `Textarea` component.

```tsx
<DataTable rows={tableRows} columns={columns} editMode noWrap />
```

```tsx
{
  field: 'description',
  headerName: 'Description',
  type: 'longText',
  componentProps: {
    minRows: 2,
    maxRows: 4,
  },
}
```

#### link

A link type. Renders as a clickable link.

```tsx
<DataTable rows={tableRows} columns={columns} noWrap />
```

```tsx
{
  field: 'website',
  headerName: 'Website',
  type: 'link',
  componentProps: ({ row }) => ({
    href: row.website,
    target: '_blank',
  }),
}
```

#### actions

A type for row-level action buttons.

```tsx
<DataTable
    rows={rows4}
    columns={columns}
    pinnedColumns={{
      right: ["actions"]
    }}
  />
```

```tsx
{
  field: 'actions',
  type: 'actions',
  getActions: ({ row }) => [
    <Button key="view" size="sm">View</Button>,
    <Button key="delete" size="sm" color="danger">Delete</Button>,
  ],
}
```

### Using componentProps

`componentProps` can be specified as an object or a function. When specified as a function, you can dynamically set props based on row data.

```tsx
// Static props
componentProps: {
  options: ['A', 'B', 'C'],
}

// Dynamic props (function)
componentProps: ({ row, id }) => ({
  options: row.availableOptions,
  disabled: row.isLocked,
})
```

## Row Interactions

### Row Hover

```tsx
<DataTable {...args} />
```

### Checkbox Selection

```tsx
<DataTable {...args} />
```

#### Controlling Selection Model

To control checkbox selection, use `selectionModel` and `onSelectionModelChange` together.

```tsx
const [selectionModel, setSelectionModel] = useState<string[]>([]);

<DataTable
  rows={rows}
  columns={columns}
  checkboxSelection
  selectionModel={selectionModel}
  onSelectionModelChange={setSelectionModel}
/>;
```

#### Notes on Selection Control

- `isRowSelectable` can control whether each row is selectable.
- `disableSelectionOnClick` prevents selection when clicking on a row.
- `isTotalSelected` is used to represent the total selection state in server pagination scenarios.

```tsx
<DataTable
  rows={rows}
  columns={columns}
  checkboxSelection
  isRowSelectable={({ row }) => row.status !== 'Closed'}
  disableSelectionOnClick
  isTotalSelected
/>
```

### Applying Selection Conditions

```tsx
<Stack height="500px" gap={1}>
    <Typography level="title-sm" textColor="text.secondary">
      status가 Closed인 행은 선택할 수 없습니다.
    </Typography>
    <DataTable
      checkboxSelection
      stripe="even"
      hoverRow
      stickyHeader
      rows={rows3}
      columns={columns}
      selectionModel={selectionModel}
      onSelectionModelChange={(newSelection) => setSelectionModel(newSelection)}
      isRowSelectable={({ row }) => row.status !== "Closed"}
    />
  </Stack>
```

### Disabling Click Selection

```tsx
<Stack height="500px">
    <Typography level="title-sm" textColor="text.secondary">
      Disable selection on click.
    </Typography>
    <DataTable
      checkboxSelection
      stripe="even"
      hoverRow
      selectionModel={selectedId}
      stickyHeader
      onSelectionModelChange={(newSelection) => setSelectedId(newSelection)}
      disableSelectionOnClick
      rows={rows4}
      columns={columns}
    />
  </Stack>
```

### Total Selection (isTotalSelected)

Used to manage the total selection state including data beyond the current page in server pagination environments.

```tsx
<Stack gap={2}>
    <Box
      sx={{
        p: 2,
        bgcolor: "primary.50",
        borderRadius: "8px"
      }}
    >
      <Typography level="body-sm">
        {isTotalSelected
          ? `All ${allRows.length} items are selected (across all pages)`
          : `${selectionModel.length} items selected on current page`}
      </Typography>
    </Box>
    <DataTable
      rows={pagedRows}
      columns={columns}
      checkboxSelection
      selectionModel={selectionModel}
      onSelectionModelChange={(newSelection, totalSelected) => {
        setSelectionModel(newSelection);
        if (totalSelected !== undefined) {
          setIsTotalSelected(totalSelected);
        }
      }}
      isTotalSelected={isTotalSelected}
      pagination
      paginationMode="server"
      rowCount={allRows.length}
      paginationModel={paginationModel}
      onPaginationModelChange={setPaginationModel}
      noWrap
    />
  </Stack>
```

```tsx
const [isTotalSelected, setIsTotalSelected] = useState(false);
const [selectionModel, setSelectionModel] = useState<string[]>([]);

<DataTable
  rows={rows}
  columns={columns}
  checkboxSelection
  pagination
  paginationMode="server"
  isTotalSelected={isTotalSelected}
  selectionModel={selectionModel}
  onSelectionModelChange={(newModel, totalSelected) => {
    setSelectionModel(newModel);
    if (totalSelected !== undefined) {
      setIsTotalSelected(totalSelected);
    }
  }}
/>;
```

## Keyboard Accessibility

DataTable supports keyboard interactions for improved accessibility.

### Shift+Click Range Selection

Hold the Shift key while clicking checkboxes to select or deselect a range of rows at once.
The selection state is applied based on the last clicked checkbox's resulting state.

```tsx
<Stack spacing={2}>
    <Typography level="body-sm">
      Hold Shift and click checkboxes to select a range of rows. The selection state is applied
      based on the first clicked checkbox&apos;s resulting state.
    </Typography>
    <DataTable
      {...args}
      selectionModel={selectionModel}
      onSelectionModelChange={setSelectionModel}
    />
    <Typography level="body-xs">Selected IDs: {selectionModel.join(", ") || "None"}</Typography>
  </Stack>
```

**How it works:**

1. Click a checkbox to select/deselect a row (this becomes the "anchor")
2. Hold Shift and click another checkbox
3. All rows between the anchor and the clicked row will be set to the same state

**Edge cases handled:**

- Works seamlessly with virtual scrolling (rows don't need to be visible)
- Selection anchor resets when data changes or page changes
- Respects `isRowSelectable` - non-selectable rows are skipped in range

### Keyboard Navigation

When a row has focus, use keyboard shortcuts to navigate and interact with rows.

```tsx
<Stack spacing={2}>
    <Typography level="body-sm">
      Click a row to focus, then use keyboard to navigate. Arrow Up/Down to move, Space to toggle
      selection, Home/End to jump to first/last row, PageUp/PageDown to move by 10 rows. Hold Shift
      with any navigation key to extend selection.
    </Typography>
    <DataTable
      {...args}
      selectionModel={selectionModel}
      onSelectionModelChange={setSelectionModel}
    />
    <Typography level="body-xs">Selected IDs: {selectionModel.join(", ") || "None"}</Typography>
  </Stack>
```

**Supported keys:**

| Key                    | Action                                      |
| ---------------------- | ------------------------------------------- |
| `↑` Arrow Up           | Move focus to previous row                  |
| `↓` Arrow Down         | Move focus to next row                      |
| `Space`                | Toggle checkbox selection                   |
| `Home`                 | Move focus to first row                     |
| `End`                  | Move focus to last row                      |
| `Page Up`              | Move focus up by 10 rows                    |
| `Page Down`            | Move focus down by 10 rows                  |
| `Shift + ↑/↓`          | Move focus and extend selection             |
| `Shift + Home/End`     | Jump to first/last row and extend selection |
| `Shift + Page Up/Down` | Move by 10 rows and extend selection        |

**Notes:**

- Click any row first to establish focus
- Tab key skips checkboxes and moves directly between rows
- Works with virtual scrolling - target row is automatically scrolled into view
- Follows WAI-ARIA Grid pattern for accessibility

## Styles and Layout

### Back Office Style

```tsx
<DataTable
    rows={args.rows}
    columns={args.columns}
    checkboxSelection={args.checkboxSelection}
    hoverRow={args.hoverRow}
    noWrap={args.noWrap}
    stripe={args.stripe}
    stickyHeader={args.stickyHeader}
    slots={args.slots}
    slotProps={args.slotProps}
    selectionModel={selectionModel}
    onSelectionModelChange={setSelectionModel}
    pagination={args.pagination}
  />
```

#### Commonly Used Table Options

- `stickyHeader`: Fixes the header
- `stripe`: Row striping (`"even" | "odd"`)
- `noWrap`: Prevents cell text wrapping
- `slots`, `slotProps`: Customize toolbar/footer/loading overlay/background

```tsx
<DataTable
  rows={rows}
  columns={columns}
  stickyHeader
  stripe="even"
  noWrap
  slots={{
    toolbar: CustomToolbar,
    footer: CustomFooter,
    loadingOverlay: CustomLoading,
  }}
  slotProps={{
    background: { style: { height: '300px' } },
  }}
/>
```

### Loading State

```tsx
<DataTable {...args} />
```

### Virtual Scrolling for Large Data

```tsx
<Stack height="500px">
    <Typography level="title-sm" textColor="text.secondary">
      Virtualized DataTable
    </Typography>
    <DataTable
      checkboxSelection
      stripe="even"
      hoverRow
      selectionModel={selectedId}
      stickyHeader
      onSelectionModelChange={(newSelection) => setSelectedId(newSelection)}
      rows={[
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4,
        ...rows4
      ].map((row, i) => ({
        ...row,
        id: i
      }))}
      columns={columns}
      initialState={{
        sorting: {
          sortModel: [
            {
              field: "number",
              sort: "asc"
            }
          ]
        }
      }}
    />
  </Stack>
```

## Slots & SlotProps Customization

DataTable allows customization of various parts through `slots` and `slotProps`.

### Available Slots

| Slot             | Description                   |
| ---------------- | ----------------------------- |
| `checkbox`       | Customize checkbox component  |
| `toolbar`        | Table top toolbar             |
| `footer`         | Table bottom footer           |
| `loadingOverlay` | Loading overlay               |
| `noRowsOverlay`  | Empty state overlay (no rows) |

### Custom Toolbar

```tsx
<DataTable
    rows={filteredRows}
    columns={columns}
    slots={{
      toolbar: CustomToolbar
    }}
    noWrap
    stickyHeader
    stripe="even"
  />
```

```tsx
const CustomToolbar = () => (
  <Box sx={{ p: 2, display: 'flex', gap: 1, borderBottom: '1px solid', borderColor: 'neutral.200' }}>
    <Button size="sm">Export</Button>
    <Button size="sm">Filter</Button>
  </Box>
);

<DataTable rows={rows} columns={columns} slots={{ toolbar: CustomToolbar }} />;
```

### Custom Footer

```tsx
<DataTable
    rows={tableRows}
    columns={columns}
    slots={{
      footer: CustomFooter
    }}
    noWrap
  />
```

```tsx
const CustomFooter = () => (
  <Box sx={{ p: 2, textAlign: 'center', borderTop: '1px solid', borderColor: 'neutral.200' }}>
    <Typography level="body-sm">Total {rows.length} items</Typography>
  </Box>
);

<DataTable rows={rows} columns={columns} slots={{ footer: CustomFooter }} />;
```

### Custom Loading Overlay

```tsx
<Stack gap={2}>
    <Button onClick={() => setLoading(!loading)}>
      {loading ? "Stop Loading" : "Start Loading"}
    </Button>
    <DataTable
      rows={tableRows}
      columns={columns}
      loading={loading}
      slots={{
        loadingOverlay: CustomLoadingOverlay
      }}
      noWrap
      slotProps={{
        background: {
          style: {
            height: "300px"
          }
        }
      }}
    />
  </Stack>
```

```tsx
const CustomLoadingOverlay = () => (
  <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2 }}>
    <CircularProgress />
    <Typography>Loading data...</Typography>
  </Box>
);

<DataTable rows={rows} columns={columns} loading slots={{ loadingOverlay: CustomLoadingOverlay }} />;
```

### No Rows Overlay

When `rows` is empty and `loading` is not `true`, a no rows overlay is displayed in the table body.

```tsx
<DataTable
  onPaginationModelChange={fn()}
  onSelectionModelChange={fn()}
  onRowClick={fn()}
  columns={[{
  field: 'dessert',
  headerName: 'Dessert (100g serving)',
  width: '40%'
}, {
  field: 'calories',
  headerName: 'Calories',
  type: 'number'
}, {
  field: 'fat',
  headerName: 'Fat (g)',
  type: 'number'
}, {
  field: 'carbs',
  headerName: 'Carbs (g)',
  type: 'number'
}, {
  field: 'protein',
  headerName: 'Protein (g)',
  type: 'number'
}]}
  rows={[]}
  noWrap
/>
```

### Custom No Rows Overlay

You can customize the empty state UI using `slots.noRowsOverlay`.

```tsx
<DataTable
    rows={[]}
    columns={tableColumns}
    noWrap
    slots={{
      noRowsOverlay: CustomOverlay
    }}
    slotProps={{
      noRowsOverlay: {
        message: "Custom message via slotProps"
      }
    }}
  />
```

```tsx
const CustomNoRowsOverlay = ({ message }: { message?: string }) => (
  <Stack alignItems="center" spacing={1}>
    <Typography level="title-md">No data available</Typography>
    <Typography level="body-sm" textColor="text.secondary">
      {message || 'Try adding new records.'}
    </Typography>
  </Stack>
);

<DataTable
  rows={[]}
  columns={columns}
  slots={{ noRowsOverlay: CustomNoRowsOverlay }}
  slotProps={{ noRowsOverlay: { message: 'Custom message via slotProps' } }}
/>;
```

### No Rows Overlay with Checkbox

The overlay correctly spans the full table width including the checkbox column.

```tsx
<DataTable
  onPaginationModelChange={fn()}
  onSelectionModelChange={fn()}
  onRowClick={fn()}
  columns={[{
  field: 'dessert',
  headerName: 'Dessert (100g serving)',
  width: '40%'
}, {
  field: 'calories',
  headerName: 'Calories',
  type: 'number'
}, {
  field: 'fat',
  headerName: 'Fat (g)',
  type: 'number'
}, {
  field: 'carbs',
  headerName: 'Carbs (g)',
  type: 'number'
}, {
  field: 'protein',
  headerName: 'Protein (g)',
  type: 'number'
}]}
  rows={[]}
  noWrap
  checkboxSelection
/>
```

### No Rows Overlay Loading Priority

When `loading` is `true`, the loading overlay takes priority over the no rows overlay.

```tsx
<Stack gap={2}>
    <Button onClick={() => setLoading(!loading)}>
      {loading ? "Stop Loading" : "Start Loading"}
    </Button>
    <Typography level="body-sm">
      {loading ? "Loading overlay is shown (noRowsOverlay hidden)" : "NoRowsOverlay is shown"}
    </Typography>
    <DataTable
      rows={[]}
      columns={tableColumns}
      loading={loading}
      noWrap
      slotProps={{
        background: {
          style: {
            height: "300px"
          }
        }
      }}
    />
  </Stack>
```

### Combined Custom Loading + No Rows Overlay

Both `loadingOverlay` and `noRowsOverlay` slots can be customized simultaneously.

```tsx
<Stack gap={2}>
    <Stack direction="row" gap={1} alignItems="center">
      <Button onClick={() => setLoading(!loading)}>
        {loading ? "Stop Loading" : "Start Loading"}
      </Button>
      <Typography level="body-xs" textColor="text.tertiary">
        {loading ? "Custom loading overlay shown" : "Custom no rows overlay shown"}
      </Typography>
    </Stack>
    <DataTable
      rows={[]}
      columns={tableColumns}
      loading={loading}
      noWrap
      slots={{
        loadingOverlay: CustomLoadingOverlay,
        noRowsOverlay: CustomNoRowsOverlay
      }}
      slotProps={{
        background: {
          style: {
            height: "300px"
          }
        }
      }}
    />
  </Stack>
```

### Custom Checkbox

```tsx
<DataTable
    rows={tableRows}
    columns={columns}
    checkboxSelection
    selectionModel={selectionModel}
    onSelectionModelChange={(newSelection) => setSelectionModel(newSelection)}
    slots={{
      checkbox: CustomCheckbox
    }}
    noWrap
  />
```

```tsx
const CustomCheckbox = (props) => (
  <Box
    onClick={props.onChange}
    sx={{
      width: 20,
      height: 20,
      borderRadius: '4px',
      border: '2px solid',
      borderColor: props.checked ? 'primary.500' : 'neutral.400',
      backgroundColor: props.checked ? 'primary.500' : 'transparent',
      cursor: 'pointer',
    }}
  >
    {props.checked && <span>✓</span>}
  </Box>
);

<DataTable rows={rows} columns={columns} checkboxSelection slots={{ checkbox: CustomCheckbox }} />;
```

### Background Styling (slotProps.background)

You can style the table background area using `slotProps.background`. Height specification is required when used with `stickyHeader`.

```tsx
<DataTable
  rows={rows}
  columns={columns}
  stickyHeader
  slotProps={{
    background: {
      style: { height: '400px' },
    },
  }}
/>
```

## Column Configuration

### Displaying id Column

```tsx
<DataTable {...args} />
```

### Customizing Column Rendering

```tsx
<DataTable
    rows={useMemo(
      () =>
        [
          ...rows3,
          ...rows3,
          ...rows3,
          ...rows3,
          ...rows3,
          ...rows3,
          ...rows3,
          ...rows3,
          ...rows3,
          ...rows3,
          ...rows3,
          ...rows3,
          ...rows3,
          ...rows3,
          ...rows3,
          ...rows3,
          ...rows3,
          ...rows3,
          ...rows3,
          ...rows3,
          ...rows3,
          ...rows3,
          ...rows3,
          ...rows3,
          ...rows3,
          ...rows3,
          ...rows3,
          ...rows3
        ].map((row, i) => ({
          ...row,
          id: i + 1
        })),
      []
    )}
    columns={columns}
    checkboxSelection
    stickyHeader
    stripe="even"
    noWrap
    slotProps={{
      background: {
        style: {
          height: "600px"
        }
      }
    }}
  />
```

### Complex UI in Cells

```tsx
<DataTable rows={rows4} columns={columns} />
```

### Description (tooltip)

```tsx
<DataTable rows={rows4} columns={columns} />
```

### Customizing Cell/Header Classes

```tsx
<DataTable
  onPaginationModelChange={fn()}
  onSelectionModelChange={fn()}
  onRowClick={fn()}
  columns={[{
  field: 'id',
  headerName: 'ID',
  width: '150px',
  cellClassName: ({
    row
  }) => row.number > 5 ? 'red' : 'blue'
}, {
  field: 'number',
  headerName: 'Number',
  type: 'number',
  width: '150px',
  cellClassName: ({
    value
  }) => value > 5 ? 'red' : 'blue'
}, {
  field: 'string',
  headerName: 'String',
  width: '600px',
  cellClassName: ({
    row
  }) => row.number > 5 ? 'red' : 'blue'
}]}
  rows={rows4}
/>
```

```tsx
<DataTable
  onPaginationModelChange={fn()}
  onSelectionModelChange={fn()}
  onRowClick={fn()}
  columns={[{
  field: 'id',
  headerName: 'ID',
  width: '150px',
  headerClassName: 'red'
}, {
  field: 'number',
  headerName: 'Number',
  type: 'number',
  width: '150px',
  headerClassName: 'red'
}, {
  field: 'string',
  headerName: 'String',
  width: '600px',
  headerClassName: 'red'
}, {
  field: 'date',
  headerName: 'Date Sort',
  width: '150px',
  renderCell: ({
    value
  }) => value.toLocaleDateString(),
  headerClassName: 'blue'
}, {
  field: 'object',
  headerName: 'Object Sort',
  width: '150px',
  renderCell: ({
    value
  }) => value.age,
  type: 'number',
  sortComparator: ({
    rowA,
    rowB
  }) => rowA.object.age - rowB.object.age,
  headerClassName: 'blue'
}]}
  rows={rows4}
  checkboxSelection
  hoverRow
  noWrap
  stripe="even"
  stickyHeader
  columnGroupingModel={[{
  groupId: 'group1',
  headerName: 'Group 1',
  headerClassName: 'red',
  children: [{
    field: 'id'
  }, {
    field: 'number'
  }, {
    field: 'string'
  }]
}, {
  groupId: 'group2',
  headerName: '',
  children: [{
    field: 'date'
  }, {
    field: 'object'
  }]
}]}
/>
```

### Column Groups

```tsx
<DataTable
  onPaginationModelChange={fn()}
  onSelectionModelChange={fn()}
  onRowClick={fn()}
  columns={[{
  field: 'id',
  headerName: 'ID',
  width: '150px'
}, {
  field: 'number',
  headerName: 'Number Sort',
  type: 'number',
  width: '900px',
  cellClassName: () => 'warn'
}, {
  field: 'string',
  headerName: 'String Sort',
  width: '150px'
}, {
  field: 'date',
  headerName: 'Date Sort',
  width: '150px',
  renderCell: ({
    value
  }) => value.toLocaleDateString(),
  cellClassName: () => 'primary'
}, {
  field: 'object',
  headerName: 'Object Sort',
  width: '150px',
  renderCell: ({
    value
  }) => value.age,
  type: 'number',
  sortComparator: ({
    rowA,
    rowB
  }) => rowA.object.age - rowB.object.age,
  cellClassName: () => 'primary'
}]}
  rows={[...rows4, ...rows4, ...rows4, ...rows4, ...rows4, ...rows4, ...rows4, ...rows4, ...rows4].map((row, i) => ({
  ...row,
  id: i,
  date: new Date(row.date),
  object: {
    age: row.object.age + i
  }
}))}
  checkboxSelection
  hoverRow
  noWrap
  stripe="even"
  stickyHeader
  columnGroupingModel={[{
  groupId: 'group1',
  headerName: 'Group 1',
  children: [{
    field: 'id'
  }, {
    field: 'number'
  }, {
    field: 'string'
  }]
}, {
  groupId: 'group2',
  headerName: '',
  children: [{
    field: 'date'
  }, {
    field: 'object'
  }]
}]}
  slotProps={{
  background: {
    style: {
      height: '300px'
    }
  }
}}
/>
```

```tsx
const columnGroupingModel = [
  {
    groupId: 'nutrition',
    headerName: 'Nutrition',
    children: [{ field: 'calories' }, { field: 'fat' }, { field: 'carbs' }],
  },
];

<DataTable rows={rows} columns={columns} columnGroupingModel={columnGroupingModel} />;
```

### Column Visibility

You can control which columns are visible using `columnVisibilityModel`.
Columns set to `false` are hidden. Columns not in the model are visible by default.
Hidden columns are completely removed from the DOM for optimal rendering performance.

```tsx
<Stack spacing={2}>
    <Stack
      direction="row"
      spacing={1}
      sx={{
        flexWrap: "wrap"
      }}
    >
      {allColumns.map((col) => (
        <label
          key={col.field as string}
          style={{
            display: "flex",
            alignItems: "center",
            gap: 4
          }}
        >
          <input
            type="checkbox"
            checked={visibilityModel[col.field as string] !== false}
            onChange={(e) =>
              setVisibilityModel((prev) => ({
                ...prev,
                [col.field as string]: e.target.checked
              }))
            }
          />
          {col.headerName}
        </label>
      ))}
    </Stack>
    <DataTable
      rows={rows2}
      columns={allColumns}
      columnVisibilityModel={visibilityModel}
      onColumnVisibilityModelChange={setVisibilityModel}
      noWrap
    />
  </Stack>
```

#### Controlled Mode

```tsx
const [visibilityModel, setVisibilityModel] = useState({ fat: false });

<DataTable
  rows={rows}
  columns={columns}
  columnVisibilityModel={visibilityModel}
  onColumnVisibilityModelChange={setVisibilityModel}
/>;
```

#### Uncontrolled Mode (initialState)

```tsx
<DataTable
  rows={rows}
  columns={columns}
  initialState={{
    columns: { columnVisibilityModel: { fat: false, carbs: false } },
  }}
/>
```

#### Column Visibility with Column Groups

```tsx
<Stack spacing={2}>
    <Stack
      direction="row"
      spacing={1}
      sx={{
        flexWrap: "wrap"
      }}
    >
      {columns.map((col) => (
        <label
          key={col.field as string}
          style={{
            display: "flex",
            alignItems: "center",
            gap: 4
          }}
        >
          <input
            type="checkbox"
            checked={visibilityModel[col.field as string] !== false}
            onChange={(e) =>
              setVisibilityModel((prev) => ({
                ...prev,
                [col.field as string]: e.target.checked
              }))
            }
          />
          {col.headerName}
        </label>
      ))}
    </Stack>
    <DataTable
      rows={rows4}
      columns={columns}
      columnGroupingModel={[
        {
          groupId: "group1",
          headerName: "Group 1",
          children: [
            {
              field: "id"
            },
            {
              field: "number"
            },
            {
              field: "string"
            }
          ]
        },
        {
          groupId: "group2",
          headerName: "Group 2",
          children: [
            {
              field: "date"
            },
            {
              field: "object"
            }
          ]
        }
      ]}
      columnVisibilityModel={visibilityModel}
      onColumnVisibilityModelChange={setVisibilityModel}
      noWrap
    />
  </Stack>
```

#### Notes

- Hidden columns are completely removed from the DOM for optimal performance.
- Sorting on hidden columns is preserved — row order is maintained even if the sort column is hidden.
- Works with column grouping: hidden columns reduce group colspan, and fully hidden groups disappear.
- Works with pinned columns: hidden pinned columns are excluded from sticky position calculations.

### Column Resizing

Setting `resizable: true` on a column allows you to adjust the column width by dragging.

```tsx
<Stack gap={1}>
    <Typography level="body-sm" textColor="text.secondary">
      Drag the column borders to resize columns
    </Typography>
    <DataTable rows={tableRows} columns={columns} noWrap />
  </Stack>
```

```tsx
const columns = [
  {
    field: 'name',
    headerName: 'Name',
    width: '200px',
    resizable: true,
  },
  {
    field: 'description',
    headerName: 'Description',
    width: '300px',
    resizable: true,
  },
];
```

### Two-Line Headers (headerLineClamp)

Setting `headerLineClamp: 2` on a column allows the header text to wrap up to 2 lines. Text exceeding 2 lines is truncated with an ellipsis, and a tooltip is displayed on hover when truncation occurs.

```tsx
<Box
    sx={{
      width: 500
    }}
  >
    <DataTable
      rows={manyRows}
      columns={[
        {
          field: "dessert",
          headerName: "Dessert Name (100g serving)",
          headerLineClamp: 2,
          width: "120px"
        },
        {
          field: "calories",
          headerName: "Calories (kcal)",
          headerLineClamp: 2,
          type: "number",
          width: "80px"
        },
        {
          field: "fat",
          headerName: "Fat Content (grams)",
          headerLineClamp: 2,
          type: "number",
          width: "80px"
        },
        {
          field: "carbs",
          headerName: "Total Carbohydrates (g)",
          headerLineClamp: 2,
          type: "number",
          width: "90px"
        },
        {
          field: "protein",
          headerName: "Protein Amount (g)",
          type: "number",
          width: "120px"
        }
      ]}
      stickyHeader
      slotProps={{
        background: {
          style: {
            height: "400px"
          }
        }
      }}
    />
  </Box>
```

```tsx
const columns = [
  {
    field: 'calories',
    headerName: 'Calories (kcal)',
    headerLineClamp: 2,
    type: 'number',
    width: '80px',
  },
  {
    field: 'fat',
    headerName: 'Fat Content (grams)',
    headerLineClamp: 2,
    type: 'number',
    width: '80px',
  },
  {
    field: 'protein',
    headerName: 'Protein (g)', // no headerLineClamp — single line (default)
    type: 'number',
  },
];
```

#### Notes

- `headerLineClamp` is opt-in per column. Columns without it remain single-line.
- Supported values: `1 | 2`.
- Works with all existing features: sorting, pinning, resizing, and column grouping.

## Column Width

Columns keep the width you specify. When every column has an explicit `width`, the table appends an
invisible filler column that absorbs the space left over, so a `200px` column renders at exactly 200px
instead of stretching to fill the container.

```tsx
<Stack gap={1}>
    <Typography level="body-sm" textColor="text.secondary">
      Three 200px columns in a 900px container. Each column keeps exactly 200px instead of
      stretching to fill the table, and dragging a resize handle moves the edge 1:1.
    </Typography>
    <Box
      sx={{
        width: "900px"
      }}
    >
      <DataTable rows={widthRows} columns={columns} noWrap />
    </Box>
  </Stack>
```

```tsx
const columns = [
  { field: 'name', headerName: 'Name', width: '200px' },
  { field: 'category', headerName: 'Category', width: '200px' },
  { field: 'calories', headerName: 'Calories', type: 'number', width: '200px' },
];
```

Dragging a resize handle moves the column edge 1:1 with the pointer — the other columns keep their
widths and the filler absorbs the difference.

```tsx
<Stack gap={1}>
    <Typography level="body-sm" textColor="text.secondary">
      Drag the handle on the Name column — the edge follows the pointer 1:1 and the other columns
      stay put.
    </Typography>
    <Box
      sx={{
        width: "900px"
      }}
    >
      <DataTable rows={widthRows} columns={columns} noWrap />
    </Box>
  </Stack>
```

### Letting a Column Fill the Remaining Space

Omit `width` on a column and it absorbs all the leftover space — no filler column is added.

```tsx
<Stack gap={1}>
    <Typography level="body-sm" textColor="text.secondary">
      Leave a column without a width and it absorbs all the leftover space, exactly as before.
    </Typography>
    <Box
      sx={{
        width: "900px"
      }}
    >
      <DataTable rows={widthRows} columns={columns} noWrap />
    </Box>
  </Stack>
```

```tsx
const columns = [
  { field: 'name', headerName: 'Name' }, // fills the remaining space
  { field: 'category', headerName: 'Category', width: '200px' },
  { field: 'calories', headerName: 'Calories', type: 'number', width: '200px' },
];
```

#### Notes

- Percentage widths (`'40%'`) resolve against the table width, so `40%` really is 40% of the table.
- When the columns are wider than the container the filler collapses to 0 and horizontal scrolling
  works as usual — pinned columns stay pinned.
- `minWidth` is enforced by the layout; `maxWidth` is only applied while dragging the resize handle.
- Dragging a resize handle now moves the column edge 1:1 with the pointer.
- Column groups and the no-rows overlay account for the filler automatically — group `colspan`
  values and the overlay's `colSpan` are unaffected.
- A custom `slots.footer` writes its own `colSpan` values. Those keep aligning with the data
  columns, but the footer will not extend under the filler column. Add one trailing empty `<td />`
  if you want the footer to span the full table width.

## Editing Features

### Inline Editing

```tsx
<div>
    <DataTable rows={rows3} columns={columns} checkboxSelection={false} noWrap editMode />
    <Button
      onClick={() => {
        console.log(editedRows);
        setIsCellEditable(true);
      }}
    >
      Submit
    </Button>
  </div>
```

#### Edit Types

- `text`, `number`, `currency`, `select`, `autocomplete`, `date`, `longText`, `link`

#### Notes on Editing

- `editMode` must be enabled for the editing UI to be active.
- Use `onCellEditStop` or `onCellEditStart` to reflect changed values.
- Specifying `renderEditCell` allows you to customize the editing UI.

```tsx
const columns = [
  {
    field: 'status',
    type: 'select',
    componentProps: { options: ['Opened', 'Preparing', 'Closed'] },
    onCellEditStop: ({ row }) => updateRow(row),
  },
  {
    field: 'note',
    type: 'longText',
    renderEditCell: ({ value }) => value.slice(0, 100),
  },
];

<DataTable rows={rows} columns={columns} editMode />;
```

### Conditional Editing

```tsx
<div>
    <Typography level="title-lg" textColor="text.secondary">
      expectedSales 100초과만 수정 가능
    </Typography>
    <DataTable rows={rows} columns={columns} checkboxSelection={false} noWrap editMode />
    <Button
      onClick={() => {
        console.log(rows);
      }}
    >
      Submit
    </Button>
  </div>
```

### Real-time Data Updates

```tsx
<DataTable rows={editRows} columns={columns} checkboxSelection={false} noWrap />
```

### Required Field Indicator

Setting `required: true` on a column displays a required indicator (\*) in the header.

```tsx
<Stack gap={1}>
    <Typography level="body-sm" textColor="text.secondary">
      Fields marked with * are required
    </Typography>
    <DataTable rows={tableRows} columns={columns} editMode noWrap />
  </Stack>
```

```tsx
const columns = [
  {
    field: 'name',
    headerName: 'Name',
    required: true,
  },
  {
    field: 'email',
    headerName: 'Email',
    required: true,
  },
];
```

### Customizing renderEditCell

Using `renderEditCell` allows you to fully customize the editing UI.

```tsx
<DataTable rows={tableRows} columns={columns} editMode noWrap />
```

```tsx
{
  field: 'rating',
  headerName: 'Rating',
  renderEditCell: ({ value, row }) => (
    <Box sx={{ display: 'flex', gap: 0.5 }}>
      {[1, 2, 3, 4, 5].map((star) => (
        <IconButton
          key={star}
          size="sm"
          onClick={() => updateRating(row.id, star)}
        >
          {star <= value ? '★' : '☆'}
        </IconButton>
      ))}
    </Box>
  ),
}
```

### Handling Edit Events

You can use `onCellEditStart` and `onCellEditStop` to detect when editing starts and ends.

```tsx
<Stack gap={2}>
    <DataTable rows={tableRows} columns={columns} editMode noWrap />
    <Box
      sx={{
        p: 2,
        bgcolor: "neutral.100",
        borderRadius: "8px",
        fontFamily: "monospace",
        fontSize: "12px"
      }}
    >
      <Typography
        level="title-sm"
        sx={{
          mb: 1
        }}
      >
        Edit Log:
      </Typography>
      {editLog.length === 0 ? (
        <Typography level="body-xs" textColor="text.secondary">
          No edits yet. Click on a cell to edit.
        </Typography>
      ) : (
        editLog.map((log) => (
          <Typography key={log} level="body-xs">
            {log}
          </Typography>
        ))
      )}
    </Box>
  </Stack>
```

```tsx
{
  field: 'value',
  headerName: 'Value',
  onCellEditStart: ({ row, originalRow, value }) => {
    console.log('Edit started:', { row, originalRow, value });
  },
  onCellEditStop: ({ row, originalRow, value }) => {
    console.log('Edit stopped:', { row, originalRow, value });
    // Save changes to server
    saveChanges(row);
  },
}
```

## Event Handlers

### onRowClick

Handles row click events. Useful for implementing Inspector patterns or detail view features.

```tsx
<Stack gap={2}>
    <DataTable
      rows={tableRows}
      columns={columns}
      hoverRow
      onRowClick={({ row }) => setSelectedRow(row)}
      noWrap
    />
    {selectedRow && (
      <Box
        sx={{
          p: 2,
          border: "1px solid",
          borderColor: "neutral.300",
          borderRadius: "8px"
        }}
      >
        <Typography level="title-md">Selected Employee Details</Typography>
        <Typography level="body-sm">Name: {selectedRow.name}</Typography>
        <Typography level="body-sm">Email: {selectedRow.email}</Typography>
        <Typography level="body-sm">Department: {selectedRow.department}</Typography>
      </Box>
    )}
  </Stack>
```

```tsx
const [selectedRow, setSelectedRow] = useState(null);

<DataTable
  rows={rows}
  columns={columns}
  hoverRow
  onRowClick={({ row, rowId }, event) => {
    console.log('Clicked row:', row, 'ID:', rowId);
    setSelectedRow(row);
  }}
/>;
```

## Sorting Features

### Basic Sorting

```tsx
<DataTable rows={rows4} columns={columns} />
```

### Custom Sort Order

```tsx
<DataTable rows={rows4} columns={columns} sortOrder={['desc', 'asc']} />
```

### Column-specific Sort Order

```tsx
<DataTable rows={rows4} columns={columns} />
```

### Disabling Sorting

```tsx
<DataTable rows={rows4} columns={columns} />
```

### Multiple Sorting

```tsx
<DataTable rows={rows4} columns={columns} />
```

### Custom Sort Logic

```tsx
<DataTable rows={rows4} columns={columns} />
```

### Controlling Sort State

#### Uncontrolled Initial Sort

```tsx
<DataTable
  onPaginationModelChange={fn()}
  onSelectionModelChange={fn()}
  onRowClick={fn()}
  columns={[{
  field: 'dessert',
  headerName: 'Dessert (100g serving)',
  width: '40%'
}, {
  field: 'calories',
  headerName: 'Calories',
  type: 'number'
}, {
  field: 'fat',
  headerName: 'Fat (g)',
  type: 'number'
}, {
  field: 'carbs',
  headerName: 'Carbs (g)',
  type: 'number'
}, {
  field: 'protein',
  headerName: 'Protein (g)',
  type: 'number'
}]}
  rows={rows}
  initialState={{
  sorting: {
    sortModel: [{
      field: 'calories',
      sort: 'asc'
    }]
  }
}}
/>
```

#### Controlled Sort

```tsx
<DataTable
    rows={rows4}
    columns={columns}
    sortModel={sortModel}
    onSortModelChange={handleSortModelChange}
  />
```

```tsx
const [sortModel, setSortModel] = useState([{ field: 'calories', sort: 'asc' }]);

<DataTable rows={rows} columns={columns} sortModel={sortModel} onSortModelChange={setSortModel} />;
```

## Pagination

### Basic Pagination

```tsx
<DataTable
  onPaginationModelChange={fn()}
  onSelectionModelChange={fn()}
  onRowClick={fn()}
  columns={[{
  field: 'dessert',
  headerName: 'Dessert (100g serving)',
  width: '40%'
}, {
  field: 'calories',
  headerName: 'Calories',
  type: 'number'
}, {
  field: 'fat',
  headerName: 'Fat (g)',
  type: 'number'
}, {
  field: 'carbs',
  headerName: 'Carbs (g)',
  type: 'number'
}, {
  field: 'protein',
  headerName: 'Protein (g)',
  type: 'number'
}]}
  rows={[...rows, ...rows, ...rows, ...rows, ...rows, ...rows, ...rows, ...rows, ...rows, ...rows, ...rows, ...rows, ...rows, ...rows, ...rows, ...rows, ...rows, ...rows, ...rows, ...rows].map((row, index) => ({
  ...row,
  id: index
}))}
  pagination
  noWrap
  slotProps={{
  background: {
    style: {
      height: '300px'
    }
  }
}}
/>
```

### Empty State

```tsx
<DataTable
  onPaginationModelChange={fn()}
  onSelectionModelChange={fn()}
  onRowClick={fn()}
  columns={[{
  field: 'dessert',
  headerName: 'Dessert (100g serving)',
  width: '40%'
}, {
  field: 'calories',
  headerName: 'Calories',
  type: 'number'
}, {
  field: 'fat',
  headerName: 'Fat (g)',
  type: 'number'
}, {
  field: 'carbs',
  headerName: 'Carbs (g)',
  type: 'number'
}, {
  field: 'protein',
  headerName: 'Protein (g)',
  type: 'number'
}]}
  rows={[]}
  pagination
  noWrap
  slotProps={{
  background: {
    style: {
      height: '300px'
    }
  }
}}
/>
```

### Sorting + Pagination

```tsx
<DataTable
    rows={rows}
    columns={columns}
    pagination
    slotProps={{
      background: {
        style: {
          height: "300px"
        }
      }
    }}
    getId={(row: RowForSort) => row.id}
  />
```

### Server Pagination

```tsx
<DataTable
    rows={pagedRows}
    columns={columns as any}
    pagination
    paginationMode="server"
    rowCount={allRows.length}
    paginationModel={paginationModel}
    onPaginationModelChange={setPaginationModel}
    loading={loading}
  />
```

You can specify the total row count using `paginationMode="server"` and `rowCount`.

```tsx
<DataTable
  rows={rows}
  columns={columns}
  pagination
  paginationMode="server"
  rowCount={totalRowCount}
  paginationModel={{ page: 0, pageSize: 20 }}
  onPaginationModelChange={setPaginationModel}
/>
```

### Dynamic rowCount

```tsx
<Stack gap={4} height="500px">
    <Stack direction="row" gap={2}>
      <Button onClick={handleIncrease}>Increase</Button>
      <Button onClick={handleDecrease}>Decrease</Button>
    </Stack>
    <DataTable rows={rows} columns={columns} pagination getId={(row: RowForSort) => row.id} />
  </Stack>
```

## Advanced Layout

### Pinned Columns

```tsx
<DataTable
    rows={args.rows}
    columns={args.columns}
    pinnedColumns={args.pinnedColumns}
    stickyHeader={args.stickyHeader}
    stripe={args.stripe}
    noWrap={args.noWrap}
    hoverRow={args.hoverRow}
    selectionModel={selectionModel}
    onSelectionModelChange={setSelectionModel}
  />
```

```tsx
<DataTable rows={rows} columns={columns} pinnedColumns={{ left: ['id', 'name'], right: ['actions'] }} />
```

## API Usage

### DataTableApi Interface

DataTable supports programmatic control through `apiRef`.

```tsx
interface DataTableApi {
  getRowIndexRelativeToVisibleRows(rowId: string): number;
  setCellFocus(rowId: string): void;
}
```

### Scrolling/Focusing to a Specific Row

```tsx
<Box
    sx={{
      height: "400px"
    }}
  >
    <DataTable
      ref={ref}
      rows={args.rows}
      columns={args.columns}
      checkboxSelection={args.checkboxSelection}
      disableSelectionOnClick={args.disableSelectionOnClick}
      selectionModel={args.selectionModel}
      isTotalSelected={args.isTotalSelected}
      pagination={args.pagination}
      paginationMode={args.paginationMode}
      paginationModel={args.paginationModel}
      noWrap={args.noWrap}
      hoverRow={args.hoverRow}
      stripe={args.stripe}
      stickyHeader={args.stickyHeader}
      initialState={args.initialState}
    />
  </Box>
```

### Inspector Pattern

```tsx
<Stack
    sx={{
      height: "100vh"
    }}
  >
    <Typography level="title-sm" textColor="text.secondary">
      Virtualized & Inspector DataTable
    </Typography>
    <Button onClick={() => apiRef.current?.setCellFocus("0")}>Row ID 0 Focus</Button>
    <Button onClick={() => apiRef.current?.setCellFocus("100")}>Row ID 100 Focus</Button>
    <div
      style={{
        flex: 1,
        maxHeight: "100%",
        overflow: "auto"
      }}
    >
      <DataTable
        ref={apiRef}
        rows={args.rows}
        columns={args.columns}
        stripe={args.stripe}
        hoverRow={args.hoverRow}
        stickyHeader={args.stickyHeader}
        disableSelectionOnClick={args.disableSelectionOnClick}
        checkboxSelection={args.checkboxSelection}
        noWrap={args.noWrap}
        selectionModel={selectedRowId === -1 ? [] : [selectedRowId]}
        onRowClick={({ rowId }) => {
          if (selectedRowId === rowId) {
            setSelectedRowId(-1);
          } else {
            console.log(rowId);
            setSelectedRowId(rowId);
            setTimeout(() => {
              apiRef.current?.setCellFocus(String(rowId));
            }, 0);
          }
        }}
      />
    </div>
    {selectedRowId !== -1 && (
      <Box
        sx={{
          backgroundColor: "aqua",
          border: "black 1px solid",
          height: "300px"
        }}
      >
        This is inspector: {selectedRowId}
      </Box>
    )}
  </Stack>
```

## Props and Customization

### DataTableProps

| Prop                            | Type                                                                | Default                 | Description                                           |
| ------------------------------- | ------------------------------------------------------------------- | ----------------------- | ----------------------------------------------------- |
| `rows`                          | `T[]`                                                               | (required)              | Array of row data objects                             |
| `columns`                       | `ColumnDef<T, ID>[]`                                                | (required)              | Column definitions array                              |
| `getId`                         | `(row: T) => ID`                                                    | -                       | Custom row identifier function (defaults to `row.id`) |
| `checkboxSelection`             | `boolean`                                                           | `false`                 | Enables checkbox selection column                     |
| `selectionModel`                | `ID[]`                                                              | -                       | Controlled selection state                            |
| `onSelectionModelChange`        | `(model: ID[], isTotalSelected?: boolean) => void`                  | -                       | Callback when selection changes                       |
| `isRowSelectable`               | `(params: { row, id }) => boolean`                                  | -                       | Determines if a row can be selected                   |
| `disableSelectionOnClick`       | `boolean`                                                           | `false`                 | Prevents selection when clicking a row                |
| `isTotalSelected`               | `boolean`                                                           | `false`                 | Represents total selection state in server pagination |
| `editMode`                      | `boolean`                                                           | `false`                 | Enables inline cell editing                           |
| `pagination`                    | `boolean`                                                           | `false`                 | Enables pagination                                    |
| `paginationMode`                | `'client' \| 'server'`                                              | `'client'`              | Client-side or server-side pagination                 |
| `paginationModel`               | `{ page: number; pageSize: number }`                                | -                       | Controlled pagination state                           |
| `onPaginationModelChange`       | `(model: { page, pageSize }) => void`                               | -                       | Callback when page or page size changes               |
| `rowCount`                      | `number`                                                            | -                       | Total row count (required for server pagination)      |
| `sortModel`                     | `SortModel<T>[]`                                                    | -                       | Controlled sort state                                 |
| `sortOrder`                     | `('asc' \| 'desc' \| null)[]`                                       | `['asc', 'desc', null]` | Allowed sort directions cycle                         |
| `onSortModelChange`             | `(model: SortModel<T>[]) => void`                                   | -                       | Callback when sort changes                            |
| `pinnedColumns`                 | `{ left?: string[]; right?: string[] }`                             | -                       | Pin columns to left/right edges                       |
| `columnGroupingModel`           | `ColumnGroupingModel`                                               | -                       | Column header grouping configuration                  |
| `columnVisibilityModel`         | `Record<string, boolean>`                                           | -                       | Controlled column visibility (false = hidden)         |
| `onColumnVisibilityModelChange` | `(model: Record<string, boolean>) => void`                          | -                       | Callback when visibility changes                      |
| `loading`                       | `boolean`                                                           | `false`                 | Shows loading overlay                                 |
| `hoverRow`                      | `boolean`                                                           | `false`                 | Highlights rows on hover                              |
| `stickyHeader`                  | `boolean`                                                           | `false`                 | Fixes the header when scrolling                       |
| `stripe`                        | `'even' \| 'odd'`                                                   | -                       | Applies striped row background                        |
| `noWrap`                        | `boolean`                                                           | `false`                 | Prevents cell text wrapping                           |
| `onRowClick`                    | `(params: { row, rowId }, event) => void`                           | -                       | Callback when a row is clicked                        |
| `slots`                         | `{ checkbox?, toolbar?, footer?, loadingOverlay?, noRowsOverlay? }` | -                       | Custom component slots                                |
| `slotProps`                     | `{ checkbox?, toolbar?, background?, noRowsOverlay? }`              | -                       | Props passed to slot components                       |
| `apiRef`                        | `React.RefObject<DataTableApi>`                                     | -                       | Imperative API reference                              |
| `initialState`                  | `{ sorting?, columns? }`                                            | -                       | Initial state for uncontrolled sort/visibility        |

### ColumnDef Union Type

All column types extend `BaseColumnDef` with shared properties:

| Prop              | Type                                                                                                            | Default    | Description                                                 |
| ----------------- | --------------------------------------------------------------------------------------------------------------- | ---------- | ----------------------------------------------------------- |
| `field`           | `keyof T`                                                                                                       | (required) | Row data field to display. Must be unique within the table. |
| `headerName`      | `string`                                                                                                        | -          | Column header text                                          |
| `type`            | `'text' \| 'number' \| 'currency' \| 'date' \| 'select' \| 'autocomplete' \| 'longText' \| 'link' \| 'actions'` | `'text'`   | Column type (determines edit UI)                            |
| `width`           | `string`                                                                                                        | -          | Column width (e.g., `'200px'`, `'30%'`)                     |
| `minWidth`        | `string`                                                                                                        | -          | Minimum column width                                        |
| `maxWidth`        | `string`                                                                                                        | -          | Maximum column width                                        |
| `resizable`       | `boolean`                                                                                                       | `false`    | Enables column resizing by dragging                         |
| `sortable`        | `boolean`                                                                                                       | `true`     | Enables sorting for this column                             |
| `sortComparator`  | `(params: { rowA, rowB }) => number`                                                                            | -          | Custom sort logic                                           |
| `sortOrder`       | `('asc' \| 'desc' \| null)[]`                                                                                   | -          | Column-specific sort direction cycle                        |
| `required`        | `boolean`                                                                                                       | `false`    | Shows required indicator (\*) in header                     |
| `headerLineClamp` | `1 \| 2`                                                                                                        | `1`        | Max header text lines before truncation                     |
| `description`     | `string`                                                                                                        | -          | Tooltip text for the column header                          |
| `cellClassName`   | `string \| ((params: { row, value }) => string)`                                                                | -          | Dynamic cell CSS class                                      |
| `headerClassName` | `string \| ((params) => string)`                                                                                | -          | Dynamic header CSS class                                    |
| `renderCell`      | `(params: { row, value, rowIndex, colIndex, id }) => ReactNode`                                                 | -          | Custom cell renderer                                        |
| `renderEditCell`  | `(params) => ReactNode`                                                                                         | -          | Custom edit cell renderer                                   |
| `isCellEditable`  | `boolean \| ((params: { row, value, id }) => boolean)`                                                          | `true`     | Whether a cell is editable                                  |
| `componentProps`  | `object \| ((params: { row, id }) => object)`                                                                   | -          | Props passed to the column type's edit component            |
| `onCellEditStart` | `(params: { row, originalRow, value }) => void`                                                                 | -          | Callback when cell editing begins                           |
| `onCellEditStop`  | `(params: { row, originalRow, value }) => void`                                                                 | -          | Callback when cell editing ends                             |

### ActionsColumnDef

For action columns, use `type: 'actions'` with `getActions`:

```tsx
{
  field: 'actions',
  type: 'actions',
  getActions: ({ row, id }) => [
    <Button key="edit" size="sm">Edit</Button>,
    <IconMenuButton key="more" items={[...]} />,
  ],
}
```

### DataTableApi

```tsx
interface DataTableApi {
  getRowIndexRelativeToVisibleRows(rowId: string): number;
  setCellFocus(rowId: string): void;
}
```

> **Note**: DataTable also accepts all Joy UI Table props (e.g., `borderAxis`, `size`, `sx`).

## Constraints and Considerations

### Required Conditions

- Using `useMemo` to maintain references when `rows` changes can reduce unnecessary re-renders.
- When using custom `getId`, values must be unique; duplicates can cause selection/sorting/editing to malfunction.
- Without height on `slotProps.background`, `stickyHeader` may not display properly.

### Feature Combination Constraints

- `pinnedColumns` and `columnGroupingModel` cannot be used simultaneously.
- `field` must be unique within a table. DataTable throws when two columns share one, because duplicates would collide on the header/`<col>` element, the measured width, and the header `id`. Whitespace is collapsed before the check, so `'order total'` and `'order_total'` also count as duplicates. To render several values in one cell, map them into `rows` first; to render a cell with no backing data, reference a `field` that is not in `rows` and draw it with `renderCell`.
- The header cell `id` (`<th id>`, referenced by each `<td headers>`) is derived from `field`, with whitespace collapsed. It is an implementation detail — do not target it from external selectors, CSS, or `aria-labelledby`. The same applies to `data-field` on the header cell.
- `editMode` must be `true` for editing-related UI to be active.
- When `paginationMode="server"`, `rowCount` must be specified.

### Performance Optimization

- Use virtual scrolling for large data (1000+ rows).
- Memoize the `columns` array with `useMemo`.
- Be careful with `renderCell` and `componentProps` functions as they can cause unnecessary re-renders.

```tsx
// Good
const columns = useMemo(() => [...], [dependencies]);

// Bad - creates a new array on every render
const columns = [...];
```
