> For the complete documentation index, see [llms.txt](https://apcom.gitbook.io/altrone-ui/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://apcom.gitbook.io/altrone-ui/components/data/datatable.md).

# DataTable

DataTable is very functional component. It not only displays data in the form of a table, but also provides great opportunities for data search. This component provides search, filtering and sorting features. But each this feature you can configure for yourself.&#x20;

With DataTable action you can extend the functionality of the table: you can create forms for you data

{% hint style="info" %}
This component requires data object type as generic T. This provides to you better code hints and additional code validation.&#x20;
{% endhint %}

```tsx
import { DataTable, DataTableColumn } from 'altrone-ui';

type Character = {
    id: number;
    name: string;
    surname: string;
} 

const data: Character[] = [{
    id: 1,
    name: 'Arnold',
    surname: 'Schwarzenegger',
    role: 'actor'
}, ...];

const columns: DataTableColumn<Character> = [{
    accessor: 'id',
    label: '#'
}, {
    accessor: 'name',
}, {
    accessor: 'surname'
}, {
    accessor: 'role'
}]

const filters: DataTableFilter<Characted> = [{
    accessor: 'role',
    type: 'select',
    label: 'Choose a role'
}]

return <DataTable<Character> 
    data={data}
    columns={columns}
    searchBy='surname'
    filters={filters}
/>
```

## Columns

The columns prop is a mandatory field for each DataTable. Through this property you can set a configuration for every column of the table. Every column of the table has to be linked with data object field through `accessor` field.&#x20;

By default, in-build cell renderer shows the value of the field. For primary types, like string or number, it works correctly, but for more complicated fields like boolean, Dates or any other objects most probably you should provide custom cell renderer via Component prop. For example, for Date type it it better to show value in a human-friendly way that in UTC-format.&#x20;

### <mark style="color:blue;">DataTableColumn</mark><mark style="color:orange;">\<T></mark>

```typescript
interface DataTableColumn<T> {
  accessor: keyof T; // key of the data object
  label?: string; // custom label
  width?: number | string; // custom width
  Component?: React.FC<DataTableCellProps>; // use this field to override default render
  visible?: boolean; // if this field is false the column is not visible. Only in 2.0 and later
}
```

## Filtering

When you have really big dataset you should provide filters for users for fast access to necessary information. Through filters prop you can easily create some filters. DataTable has three types of filters:

**Select.** This filter adds [Select](/altrone-ui/components/forms/select.md) component where you can choose only one options out of all possible options.&#x20;

**CheckboxList:** This filter adds list of [Checkbox](/altrone-ui/components/forms/checkbox.md) components where you can select some options out of all possible options.&#x20;

**Checkbox &#x20;**<mark style="color:purple;background-color:purple;">**new**</mark>**&#x20;.** This filter was added in **Altrone 2.0**. This filter adds single [Checkbox](/altrone-ui/components/forms/checkbox.md) component. This component works with boolean-fields of data object.&#x20;

User can use one or more filters. Number of applied filters shows on indicator of the "Filters" button.&#x20;

### <mark style="color:blue;">DataTableFilter</mark><mark style="color:orange;">\<T></mark>

```typescript
interface DataTableFilter<T> {
  accessor: keyof T; // key of the data object
  type: 'select' | 'checkboxList' | 'checkbox'; // filter type
  label?: string; // custom label of the filter. By default, the label is equals of column label or accessor
  defaultValue?: unknown; // default value of the filter
}
```

## Sorting

By default the order is determined by the order in which the data array was passed. By user can change change sorting. To add "Sort" button you have to provide `sortBy` prop with array of available props for sorting.&#x20;

Default sorting function works correctly with primary data types. But if you have a complicated data structure so you should write your custom sorting function in `sortFunc` prop.&#x20;

### <mark style="color:blue;">DataTableSearchFunc</mark><mark style="color:orange;">\<T></mark>

<pre class="language-typescript"><code class="lang-typescript">interface DataTableSortFunc&#x3C;T> {
  itemA: T; // first item
  itemB: T; // second item
  field: keyof T; // field key to sort by
  direction: <a data-footnote-ref href="#user-content-fn-1">Sort</a>; // direction of the sorting
}
</code></pre>

## Search

Search field allows to find one or more records that match the search query. Default search function works only with only one field of primary type. But you can write a more complicated search logic via `searchFunc` prop.&#x20;

### <mark style="color:blue;">DataTableSearchFunc</mark><mark style="color:orange;">\<T></mark>

```typescript
interface DataTableSearchFunc<T> {
  item: T; // item
  field: keyof T; // field key to search by
  query: string; // user's value in search field
}
```

## DataTable Actions

By default, every DataTable has two build-in actions: sorting (when you passed `sortBy` prop) and filtering (when you passed `filters` prop). But in **Altrone 1.1** and later you can also create your own actions. You have to pass array with [DataTableAction](#datatableaction) objects into `actions` prop.&#x20;

There are three types of DataTable actions:

**Button.** To activate this type of action you have to pass `onClick` prop. When user clicks on the action `onClick` callback runs. For example, "Refresh" action.&#x20;

**Context Menu.** To activate this type of action you have to pass `contextMenu` prop. When user clicks on the action he see the list of the actions in the dropdown. For example: "Group by" action.&#x20;

**Popup.** To activate this type of action you have to pass `content` prop. When user clicks on the action he see the FloatingBox with the content which you passed in `content` prop. Content prop is a function which accepts [DataTablePopupActionProps](#datatablepopupactionprops) argument and show the result of the function. For example: "Add" action.&#x20;

### <mark style="color:blue;">DataTablePopupActionProps</mark>

```typescript
interface DataTablePopupActionProps {
  closePopup: () => void; 
}
```

### <mark style="color:blue;">DataTableAction</mark>

<pre class="language-typescript"><code class="lang-typescript">interface DataTableAction {
  icon: JSX.Element;
  label: string;
  onClick?: () => void;
  isIcon?: boolean;
  danger?: boolean;
  content?: (args: <a data-footnote-ref href="#user-content-fn-2">DataTablePopupActionProps</a>) => JSX.Element;
  contextMenu?: ContextMenuType;
  indicator?: Indicator;
  disabled?: boolean; // only in Altrone 1.3 and later
}
</code></pre>

## Selection Mode

In Altrone 1.3 selection mode was introduced for DataTable. When this mode is active you can see checkbox icon in the top left corner of the table. When user clicks on this icon he activates  selection mode.&#x20;

In selection mode user can select one or more rows of the table. In selection mode normal actions are not working. But you can define special actions which work only in selection mode. To do that you have to pass array of actions in `selectableActions` prop. The interface of [DataTableSelectableAction](#datatableselectableaction-less-than-t-greater-than) are very similar to [DataTableAction](#datatableaction), but there are some slighty differences, like array of selected rows in `onClick` and `content` properties.&#x20;

### <mark style="color:blue;">DataTableSelectableAction</mark><mark style="color:orange;">\<T></mark>

```typescript
interface DataTableAction {
  icon: JSX.Element;
  label: string;
  onClick?: (selectedRows: T[]) => void;
  isIcon?: boolean;
  danger?: boolean;
  content?: (args: DataTablePopupActionProps & { selectedRows?: T[] }) => JSX.Element;
  contextMenu?: ContextMenuType;
  indicator?: Indicator;
  disabled?: boolean;
}
```

## Statusbar

Every DataTable has a statusbar at the bottom of the table. This statusbar shows some useful information like total rows. When you use filters the status bar also shows to you how many rows were match with applied filters.&#x20;

You can create your own statusbar with DataTableStatusComponent property. You can use DataTableContext to get all necessary data about the table.&#x20;

## DataTable Context

All inner components of DataTable use DataTableContext to access data of the table. You can use this context in your custom components as well. To do that you have to use hook `useDataTableContext`.&#x20;

```typescript
const {
  data, // data of the table (after filtering and sorting)
  initialData, // data of the table
  columns, // configuration of the table
  page, // current page
  setPage, // move to the page (page: number) => void
  limit, // number of rows on the page
  searchBy, // searchBy accessor
  search: '', // search query
  setSearch: () => null, // change search query (search: string) => void
  sortKeys: [], // sort accessors
  sortBy: null, // selected sort accessor
  sortType: Sort.asc, // sort direction
  setSortBy: () => null, // change sort accessor (sortBy: keyOf T) => void
  setSortType: () => null, // change sort direction (direction: Direction) => void
  filters: [], // filters configurations
  appliedFilters: [], // applied filters by user
  setAppliedFilters: () => null, // change applied filters (filters: { accessor: keyof T, value: any }) => void
  mobileColumns: [], // mobile columns 
  selectableMode, // is selectable mode activated 
  setSelectableMode: () => null, // set selectable mode (mode: boolean) => void
  selectedRows: [], // indexes of selected rows
  selectRow: () => null // select the row (rowIndex: number) => void
} = useDataTableContext();
```

## Adaptive design

On mobile devices it is hard to fit all the table on one screen. By default, DataTable shows only the first column and hides rest columns under the "..." button. When user clicks on "..." button he sees the modal with all columns of the selected row.&#x20;

But you can manage with visible columns on mobile devices. You can use another column or you can show some columns on the screen. Just pass necessary accessors in `mobileColumns` property.&#x20;

## Properties <mark style="color:orange;">(\<T extends object>)</mark>

| Property                                             | Type                                       | Description                                                                                                                                                                                                                          |
| ---------------------------------------------------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **`data`**<mark style="color:red;">**`*`**</mark>    | `T[]`                                      | Data set                                                                                                                                                                                                                             |
| **`columns`**<mark style="color:red;">**`*`**</mark> | `DataTableColumn<T>[]`                     | Column configuration                                                                                                                                                                                                                 |
| **`limit`**                                          | `number`                                   | Number of rows on the page. Default value is 20                                                                                                                                                                                      |
| **`searchBy`**                                       | `keyof T`                                  | Field key to search by. If this prop is set user can see search field in the header                                                                                                                                                  |
| **`sortKeys`**                                       | `(keyof T)[]`                              | Field keys to sort by. If this prop is set user can see "Sort" button in the header                                                                                                                                                  |
| **`sortFunc`**                                       | `(params: DataTableSortFunc) => number`    | Custom [sort](#sorting) function for complicated dataset                                                                                                                                                                             |
| **`searchFunc`**                                     | `(params: DataTableSearchFunc) => boolean` | Custom [search](#search) function for complicated dataset                                                                                                                                                                            |
| **`filters`**                                        | `DataTableFilter<T>[]`                     | Set of [filters](#filtering). If this prop is set user can see "Filters" button in the header                                                                                                                                        |
| **`mobileColumns`**                                  | `(keyof T)[]`                              | <p>With this property you can set visible columns on mobile devices. By default you can see only the first column. Rest of them user can open only by clicking on "..." button. <br><br><a href="#adaptive-design">Read more</a></p> |
| **`striped`**                                        | `'odd' \| 'even'`                          | This property set background for odd or even rows of the table. Default value is undefined. This prop is available only in **Altrone 1.2** and later                                                                                 |
| **`actions`**                                        | `DataTableAction[]`                        | Custom [DataTable actions](#datatable-actions). This prop is available only in **Altrone 1.1** and later                                                                                                                             |
| **`selectable`**                                     | `boolean`                                  | Add special button in the header which activates [selection mode](#select-mode). This prop is available only in **Altrone 1.3** and later                                                                                            |
| **`selectableActions`**                              | `DataTableSelectionAction[]`               | List of custom actions for [selection mode](#select-mode). This prop is available only in **Altrone 1.3** and later                                                                                                                  |
| **`DataTableStatusComponent`**                       | `() => JSX.Element`                        | Custom status bar. This prop is available only in **Altrone 1.3** and later                                                                                                                                                          |
| **`className`**                                      | `string`                                   | Custom CSS class                                                                                                                                                                                                                     |

## History

* **`Altrone 2.0`**:
  * replaced old search field with new [Search](#search) component
  * replaced old pagination with new [Pagination](/altrone-ui/components/indicators/pagination.md) component
  * added `visible` prop for [DataTableColumn](#datatablecolumn-less-than-t-greater-than)
  * added `checkbox` variant for [DataTableFilter](#datatablefilter-less-than-t-greater-than)
* **`Altrone 1.3`**:
  * added `selectable` prop
  * added `selectableActions` prop
  * added `disabled` prop for [DataTableAction](#datatableaction) and [DataTableSelectableAction](#datatableselectableaction-less-than-t-greater-than)
  * added `DataTableStatusComponent` prop
* **`Altrone 1.2`**:
  * added `striped` prop
  * added clear button for search field
* **`Altrone 1.1`**:
  * added `actions` prop
  * added indicators for "Filters" action
* **`Altrone 1.0`**: initial release

[^1]: [Sort](/altrone-ui/utils/enums/sort.md) interface

[^2]: [DataTablePopupActionProps](#datatablepopupactionprops)
