Table

Maintainer:
Raubzeug
GitHub
verticalAlign
rowActionsSize
edgePadding
import {Table} from '@gravity-ui/uikit';

A Table allows selecting and sorting rows, as well as performing actions on a row.

Properties

NameDescriptionTypeDefault
dataDataany[]
columnsColumn settingsTableColumnConfig[]
verticalAlignVertical alignment of content"top" "middle"
getRowDescriptorHandler to get the row descriptor(item: any, index: number) => DescriptorType
getRowIdRow ID used when selecting and sorting rows. If you skip a row, its ID will be the value of the field in the row data with the same name as the column ID.string ((item: any, index: number) => string)
getRowClassNamesRow CSS classes(item: any, index: number) => string[]
isRowDisabledCondition for disabling columns(item: any, index: number) => boolean
onRowClickRow click handler(item: any, index: number, event: React.MouseEvent<HTMLTableRowElement>) => void
onRowMouseEnterRow mouseenter handler(item: any, index: number, event: React.MouseEvent<HTMLTableRowElement>) => void
onRowMouseLeaveRow mouseleave handler(item: any, index: number, event: React.MouseEvent<HTMLTableRowElement>) => void
emptyMessageReturning a message if the data is missingstring"No data"
classNameTable CSS classstring
edgePaddingAdds horizontal padding for edge cellsboolean
stickyHorizontalScrollAdds a horizontal sticky scroll in a table. Note: A table cannot have a fixed height and a sticky scroll at the same time. A sticky scroll will not work if the table has an overflow.booleanfalse
stickyHorizontalScrollBreakpointThreshold the parent block should reach before making a scroll sticky. This is useful in the console, such as when the groupActions bar overlaps the scroll.number0

DescriptorType

NameDescriptionTypeDefault
idRow ID used when selecting and sorting rowsstring
disabledCondition for disabling columnsboolean
interactiveShow row hoverboolean
classNamesRow CSS classesstring[]

TableColumnConfig

NameDescriptionTypeDefault
idColumn IDstring
nameColumn name (header)string (() => React.ReactNode)column ID
classNameCSS class that will be added to all cells in the columnstring
placeholderStub when there is no data in a cellstring ((item: any, index: number) => React.ReactNode)— (&mdash;)
templateCell contents. If you skip a row, the cell contents will be the value of the field with the same name as this row.string ((item: any, index: number) => React.ReactNode)Value of the field with the name equal to the column ID
alignContent alignment"start" "center" "end"
stickySticky column"start" "end"
primaryIdentifies a column as primary as opposed to othersboolean
widthColumn's content width in pixelsnumber string
metadisplayName: name to be shown in Table Settings widget; other miscellaneous data including the HOC settingsRecord<string, any>

Using Table with the withTableActions HOC

This HOC adds a special column with actions to table columns.

Properties

NameDescriptionType
getRowActionsArray of action configs for each row(item: any, index: number) => TableActionConfig[]
renderRowActionsRender function for Actions Cell(props: {item: any; index: number}) => React.ReactNode
rowActionsSizeSize of the action button and popup menu items"s" "m" "l" "xl"
rowActionsIconCustom Icon for Actions CellReact.ReactNode

TableActionConfig

type TableActionConfig = TableAction | TableActionGroup;

TableAction

NameDescriptionTypeDefault
textTextstring
handlerClick handler(item: any, index: number) => void
disabledAction disabledboolean
hrefA menu item with this property becomes a link to the specified location.string
targetSame as the target attribute of the <a> tag.string
relSame as the rel attribute of the <a> tag.string
themeTheme"normal" "danger""normal"
iconIcon to display next to the textReact.ReactNode

TableActionGroup

NameDescriptionType
titleAction group headerstring
itemsAction group itemsTableActionConfig[]

Example

import {Table, withTableActions} from '@gravity-ui/uikit';

const MyTable = withTableActions(Table);
const data = [
  {id: 1, text: 'Hello'},
  {id: 2, text: 'World'},
];
const columns = [{id: 'id'}, {id: 'text'}];
const getRowActions = () => {
  return [
    {
      text: 'Print',
      handler: () => {},
    },
    {
      text: 'Remove',
      handler: () => {},
      theme: 'danger',
    },
  ];
};

const table = <MyTable data={data} columns={columns} getRowActions={getRowActions} />;
import {Table, withTableActions, RenderRowActionsProps} from '@gravity-ui/uikit';

const MyTable = withTableActions(Table);
type Item = {id: number; text: string};

const data: Item[] = [
  {id: 1, text: 'Hello'},
  {id: 2, text: 'World'},
];
const columns = [{id: 'id'}, {id: 'text'}];

const RowAction = ({item}: RenderRowActionsProps<Item>) => {
    return <React.Fragment>{`Action for - ${item.text}`}</React.Fragment>;
};

const table = (
  <MyTable
    data={data}
    columns={columns}
    renderRowActions={RowAction}
  />
);

Using Table with the withTableCopy HOC

This HOC enables copying the contents of a cell or any other text.

ColumnMeta

NameDescriptionType
copyText to copy. If the value is true, copying cell contents is allowed.boolean ((item: any, index: number) => string) ((item: any, index: number) => number)

Example

import {Table, withTableCopy} from '@gravity-ui/uikit';

const MyTable = withTableCopy(Table);
const data = [
  {id: 1, text: 'Hello'},
  {id: 2, text: 'World'},
];
const columns = [
  {id: 'id', meta: {copy: ({id}) => `ID #${id}`}},
  {id: 'text', meta: {copy: true}},
];

const table = <MyTable data={data} columns={columns} />;

Using Table with the withTableSelection HOC

This HOC enables selecting table rows.

Properties

NameDescriptionType
selectedIdsSelected rowsstring[]
onSelectionChangeSelected row change handler(ids: string[]) => void

Example

import {Table, withTableSelection} from '@gravity-ui/uikit';

const MyTable = withTableSelection(Table);
const data = [
  {id: 1, text: 'Hello'},
  {id: 2, text: 'World'},
];
const columns = [{id: 'id'}, {id: 'text'}];
const getRowId = 'id';

function SelectionTable() {
  const [selectedIds, setSelectedIds] = React.useState([1]);

  return (
    <MyTable
      data={data}
      columns={columns}
      getRowId={getRowId}
      selectedIds={selectedIds}
      onSelectionChange={setSelectedIds}
    />
  );
}

Using Table with the withTableSettings HOC

This HOC enables features for table column settings. You can use it in two ways:

import {Table, withTableSettings} from './withTableSettings';

// No options passed
const MyTable1 = withTableSettings(Table);
// or with options
const MyTable1 = withTableSettings({sortable: false})(Table);

Options

NameDescriptionTypeDefault
widthSettings popup widthnumber "fit"
sortableEnables or disables sorting settings itemsbooleantrue
filterableEnables or disables filtering settings itemsbooleanfalse

ColumnMeta

NameDescriptionTypeDefault
selectedByDefaultEnables or disables selecting a column if it is missing from the settingsbooleantrue
selectedAlwaysMakes the column always selected. You cannot change its visibility.booleanfalse

Properties

NameDescriptionType
settingsPopupWidthTableColumnSetup pop-up widthnumber "fit"
settingsCurrent settingsTableSettingsData
updateSettingsSettings update handler(data: TableSettingsData) => Promise<void>
renderControlsEnables rendering custom actionsRenderControls
settingsFilterPlaceholderText that appears in the control when no search value is setstring
settingsFilterEmptyMessageText that appears when no item is foundstring
filterSettingsFunction for filtering items(value: string, item: TableColumnSetupItem) => boolean

TableSettingsData

type TableSettingsData = Array<{
  id: string;
  isSelected?: boolean;
}>;

RenderControls

type RenderControls = (params: {
  DefaultApplyButton: React.ComponentType;
  onApply: () => void;
}) => React.ReactNode;

Example

import {Table, withTableSettings} from '@gravity-ui/uikit';

const MyTable = withTableSettings({width: 100, sortable: false})(Table);
const data = [
  {id: 1, text: 'Hello'},
  {id: 2, text: 'World'},
];
const columns = [{id: 'id'}, {id: 'text'}];
const initialSettings = [
  {id: 'id', isSelected: false},
  {id: 'text', isSelected: true},
];

function SelectionTable() {
  const [settings, setSettings] = React.useState(initialSettings);

  return (
    <MyTable
      data={data}
      columns={columns}
      settings={settings}
      updateSettings={(settings) => {
        setSettings(settings);
        return Promise.resolve();
      }}
      renderControls={({DefaultApplyButton, onApply}) => (
        <Flex gapRow="1" direction="column">
          <Button
            view="outlined-warning"
            onClick={() => {
              onApply();
              setSettings(initialSettings);
            }}
          >
            Reset
          </Button>
          <DefaultApplyButton />
        </Flex>
      )}
    />
  );
}

Using Table with the withTableSorting HOC

This HOC enables column sorting.

ColumnMeta

NameDescriptionTypeDefault
defaultSortOrderSets the primary sorting order"asc" "desc"asc
sortSorting function. It should return a value for sorting in the ascending order. If set to true, the cell values are compared and sorted in the ascending order.boolean ((itemA: any, itemB: any) => number)

Properties

NameDescriptionType
defaultSortStateDefault sorting state for an uncontrolled componentTableSortState
sortStateSorting stateTableSortState
onSortStateChangeSorting state change handle(sortState: TableSortState) => void

If the sortState and onSortStateChange properties are missing, the sorting state is stored in the component itself.

TableSortState

type TableSortState = Array<{
  column: string;
  order: 'asc' | 'desc';
}>;

Example

import {Table, withTableSorting} from '@gravity-ui/uikit';

const MyTable = withTableSorting(Table);
const data = [
  {id: 1, text: 'Hello', date: '2016-10-25'},
  {id: 2, text: 'World', date: '2020-08-15'},
];
const columns = [
  {id: 'id', meta: {sort: true}},
  {
    id: 'text',
    meta: {defaultSortOrder: 'desc', sort: (a, b) => Date.parse(a.date) - Date.parse(b.date)},
  },
];

const table = <MyTable data={data} columns={columns} />;