# TableGridSwitch

**Category:** Base Components/Collections/TableGridSwitch/TableGridSwitch

## Design

### Description

The `TableGridSwitch` component provides a pair of icons in the toolbar for toggling between `Grid` and `Table` views. The icon order is fixed: `Table` view is on the left, and `Grid` view is on the right.

#### Usage

1. Wrap your code in a `WixDesignSystemProvider` followed by a [`WixPatternsProvider`](./?path=/story/base-components-providers--wixpatternsprovider).
1. Wrap `TableGridSwitch` in a [`CollectionPage`](./?path=/story/base-components-pages-collection-page--collectionpage).
1. Create a [`TableGridSwitchState`](./?path=/story/base-components-collections-tablegridswitch-tablegridswitchstate--tablegridswitchstate) using [`useTableGridSwitchCollection()`](./?path=/story/base-components-collections-tablegridswitch-usetablegridswitchcollection--usetablegridswitchcollection).
1. Pass the `TableGridSwitchState` to the `state` prop.

```tsx
import { TableGridSwitch, useTableGridSwitch } from '@wix/patterns';
```

### Basic table grid switch

A basic table and grid switch. Use the icons in the toolbar to toggle between a Grid view and a Table view.

```tsx
import { Avatar, Text } from '@wix/design-system';
import React from 'react';
import { Delete } from '@wix/wix-ui-icons-common';
import { CollectionPage } from '@wix/patterns/page';
import {
  OffsetQuery,
  TableGridSwitch,
  useTableGridSwitchCollection,
} from '@wix/patterns';
import { contacts } from '@wix/crm';

function TableGridSwitchNoLeftElements() {

  const state = useTableGridSwitchCollection<contacts.Contact>({
    queryName: 'contacts-ToolbarFilters',
    fetchData: (query: OffsetQuery) => {
      const { limit, offset, search, filters } = query;

      let queryBuilder = contacts.queryContacts().limit(limit).skip(offset);

      return queryBuilder.find().then(({ items = [], totalCount: total }) => ({
        items,
        total,
      }));
    },
    itemName: (item) => `${item.info?.name?.first} ${item.info?.name?.last}`,
    fetchErrorMessage: () => 'Error fetching contacts',
    filters: {},
  });

  return (
    <CollectionPage height="400px">
      <CollectionPage.Header title={{ text: 'Contacts' }} />
      <CollectionPage.Content>
        <TableGridSwitch
          search={false}
          state={state}
          columns={[
            {
              title: '',
              width: '50px',
              render: (contact) => (
                <Avatar
                  name={`${contact.info?.name?.first} ${contact.info?.name?.last}`}
                  imgProps={{ src: contact.info?.picture?.image }}
                />
              ),
            },
            {
              title: 'Name',
              width: '250px',
              render: (contact) =>
                `${contact.info?.name?.first} ${contact.info?.name?.last}`,
            },
            {
              title: 'Last Activity',
              render: (contact) =>
                contact.lastActivity?.activityDate?.toLocaleString(),
            },
          ]}
          actionCell={(item, index, api) => {
            return {
              primaryAction: {
                text: 'Edit',
                onClick: () => {},
              },
              secondaryActions: [
                {
                  text: `Delete contact`,
                  icon: <Delete />,
                  onClick: () => {
                    api.openConfirmDeleteModal({
                      content: (
                        <Text>
                          Are you sure want to delete &nbsp;
                          <Text weight="bold">{`${item.info?.name?.first} ${item.info?.name?.last}`}</Text>{' '}
                          contact?
                        </Text>
                      ),
                      primaryButtonOnClick: () => {},
                    });
                  },
                },
              ],
            };
          }}
        />
      </CollectionPage.Content>
    </CollectionPage>
  );
}
```

### Custom columns

A basic table and grid switch with [custom columns](./?path=/story/features-display--customcolumns). Note that custom columns are only available in the Table view.

```tsx
import { Avatar, Text } from '@wix/design-system';
import React from 'react';
import { Delete } from '@wix/wix-ui-icons-common';
import { CollectionPage } from '@wix/patterns/page';
import {
  OffsetQuery,
  TableGridSwitch,
  useTableGridSwitchCollection,
  CustomColumns,
} from '@wix/patterns';
import { contacts } from '@wix/crm';

function TableGridSwitchAdvanceSorting() {

  const state = useTableGridSwitchCollection<contacts.Contact>({
    queryName: 'contacts-ToolbarFilters2',
    fetchData: (query: OffsetQuery) => {
      const { limit, offset, search, filters } = query;

      let queryBuilder = contacts.queryContacts().limit(limit).skip(offset);

      return queryBuilder.find().then(({ items = [], totalCount: total }) => ({
        items,
        total,
      }));
    },
    itemName: (item) => `${item.info?.name?.first} ${item.info?.name?.last}`,
    fetchErrorMessage: () => 'Error fetching contacts',
    filters: {},
  });

  return (
    <CollectionPage height="400px">
      <CollectionPage.Header title={{ text: 'Contacts' }} />
      <CollectionPage.Content>
        <TableGridSwitch
          search={false}
          state={state}
          customColumns={<CustomColumns />}
          columns={[
            {
              id: 'avatar',
              title: '',
              hideable: true,
              width: '50px',
              render: (contact) => (
                <Avatar
                  name={`${contact.info?.name?.first} ${contact.info?.name?.last}`}
                  imgProps={{ src: contact.info?.picture?.image }}
                />
              ),
            },
            {
              title: 'Name',
              width: '250px',
              render: (contact) =>
                `${contact.info?.name?.first} ${contact.info?.name?.last}`,
            },
            {
              title: 'Last Activity',
              render: (contact) =>
                contact.lastActivity?.activityDate?.toLocaleString(),
            },
          ]}
          actionCell={(item, index, api) => {
            return {
              primaryAction: {
                text: 'Edit',
                onClick: () => {},
              },
              secondaryActions: [
                {
                  text: `Delete contact`,
                  icon: <Delete />,
                  onClick: () => {
                    api.openConfirmDeleteModal({
                      content: (
                        <Text>
                          Are you sure want to delete &nbsp;
                          <Text weight="bold">{`${item.info?.name?.first} ${item.info?.name?.last}`}</Text>{' '}
                        </Text>
                      ),
                      primaryButtonOnClick: () => {},
                    });
                  },
                },
              ],
            };
          }}
        />
      </CollectionPage.Content>
    </CollectionPage>
  );
}
```

## API

### Props

| Prop | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `state` | `TableGridSwitchState<T, F>` | Yes | - | A `TableGridSwitchState` instance created using [useTableGridSwitch](./?path=/story/base-components-collections-tablegridswitch-usetablegridswitchcollection--usetablegridswitchcollection). |
| `dragAndDrop` | `{ grid: { SortableContext: (<T, F extends FiltersMap>(props: GridSortableContextProps<T, F>) => Element) & { displayName: string; }; DraggableCard: (<T, F extends FiltersMap>(props: DraggableCardProps<...>) => Element) & { ...; }; DraggableCardOverlay: (<T, F extends FiltersMap>(props: DraggableCardOverlayProps<...>...` | No | - | Adds functionality to allow visitors to reorder items manually. For more information, see the [Drag and Drop Overview](./?path=/story/features-sort-drag-and-drop--overview). |
| `sections` | `{ GridSections: (<T, F extends FiltersMap>(props: GridSectionsContentProps<T, F>) => Element) & { displayName: string; }; TableSections: (<T, F extends FiltersMap>({ groupBy, renderSection, table, columns, rowDetails, collapsible, events, ...collectionTableProps }: TableSectionsProps<...>) => Element) & { ...; }; gr...` | No | - | Configuration for rendering sections. When provided, the component will render with section headers that group related rows together for both Grid and Table views. |
| `search` | `boolean \| FilterElement<any> \| CollectionSearchElement` | No | `true` | Displays a search input on the right side of the table toolbar.<br> <br> Accepts a boolean or a custom React element as a parameter. When passing `false`, no search input is displayed. |
| `title` | `ToolbarTitleElement` | No | - | Displays a title at the left of a toolbar. Accepts a [ToolbarTitle](./?path=/story/features-display-toolbar--toolbartitle) component. |
| `tags` | `TagsElement<T, F>` | No | - | Enables tags feature. In this element you can pass the configuration |
| `errorState` | `((err: unknown, params: { isOnline: boolean; retry: () => void; }) => ReactElement<any, string \| JSXElementConstructor<any>>)` | No | - | A render function to be rendered when there's an error fetching data from the server.<br> The function accepts the following parameters <br> * `err`: The error thrown by the [fetchData](./?path=/story/common-hooks--usecollection) function <br> * `isOnline`: Indicates whether internet connection is available <br> * `retry`: Retry collection fetch on failed response, similar to `collection.retryFetch` <br> Returns [`EmptyState`](https://www.docs.wixdesignsystem.com/?path=/story/components-layout--emptystate) component. |
| `views` | `CollectionViewsDropdownElement<F>` | No | - | Adds view options to the table headers. Accepts a [Views](./?path=/story/features-display-views--views) component. |
| `filters` | `CollectionToolbarFiltersElement` | No | - | Adds filters to the toolbar and/or a sliding panel. Accepts a `ToolbarFilters` component, which must have the `panelTitle` prop defined. |
| `tabs` | `TabsFilterElement<TabsFilterProps<T>>` | No | - | Displays tabs at the left of a toolbar. Accepts a [TabsFilter](./?path=/story/features-filter-components--tabsfilter) component. |
| `minCardHeight` | `MinHeight<string \| number>` | No | `300px` | Minimum height for a card's container when showing:<br> - A loader<br> - Empty state<br> - Error state <br><br> If no unit is specified, `px` is used. |
| `renderError` | `((params: { err: unknown; isOnline: boolean; retry: () => void; }) => ReactElement<any, string \| JSXElementConstructor<any>>)` | No | - | A render function to be rendered when there's an error fetching data from the server.<br> The function accepts the following parameters <br> * `err`: The error thrown by the [fetchData](./?path=/story/common-hooks--usecollection) function <br> * `isOnline`: Indicates whether internet connection is available <br> * `retry`: Retry collection fetch on failed response, similar to `collection.retryFetch` <br> Returns [`EmptyState`](https://www.docs.wixdesignsystem.com/?path=/story/components-layout--emptystate) component. @deprecated Use `errorState` instead. |
| `emptyState` | `ReactNode` | No | - | Renders when there are no items to display. Accepts a [`CollectionEmptyState`](./?path=/story/features-display-empty-states--collectionemptystate) component. |
| `noResultsState` | `ReactNode \| ((params: { hasAvailableItems: boolean; query: ComputedQuery<F>; }) => ReactNode)` | No | - | Shown when a search or filter has no results. Accepts a [`CollectionNoResultsState`](./?path=/story/features-display-empty-states--collectionnoresultsstate) component, or a function that accepts the following parameters: - `hasAvailableItems`: Indicates whether other items may be shown using other filter or search parameters. - `query`: An instance of [`ComputedQuery`](./?path=/story/common-models--computedquery) representing the query that resulted in the empty state. The function should return [`CollectionNoResultsState`](./?path=/story/features-display-empty-states--collectionnoresultsstate). |
| `topNotification` | `boolean \| TopNotificationElement \| ((params: { query: ComputedQuery<F>; }) => boolean \| TopNotificationElement \| null) \| null` | No | - | Renders a notification below the header. Accepts a [`TableTopNotification`](./?path=/story/features-display-tabletopnotification--tabletopnotification) component. |
| `summaryBar` | `ReactNode` | No | - | Display a summary bar below the toolbar. Accepts a [`SummaryBar`](./?path=/story/features-display-toolbar--summarybar) component. |
| `dragAndDropSubmit` | `DragAndDropSubmit<T, F>` | No | - | Function that submits a drop event to the server. <br> <br> The parameter is an event object containing the following details: <br> -`from: {item: T; index: number}`: The dragged item. <br> -`after: null \| [item: T; iindex: number}`: The previous dropped item. If this is the first item to be dropped, this argument is `null`. <br> -`filters`: Applied [Drag and Drop](./?path=/story/features-sort-drag-and-drop--overview) filters. @returns Promise |
| `dragAndDropBulkSubmit` | `DragAndDropBulkSubmit<T, F>` | No | - | Function that submits an array of drop events to the server. <br> <br> The parameter is an array of event objects containing the following details: <br> -`from: {item: T; index: number}`: The dragged item. <br> -`after: null \| [item: T; index: number}`: The previous dropped item. If this is the first item to be dropped, this argument is `null`. <br> -`filters`: Applied [Drag and Drop](./?path=/story/features-sort-drag-and-drop--overview) filters. <br> @returns Promise |
| `dragAndDropCancel` | `DragAndDropCancel<T, F>` | No | - | A function that cancels a drop event. <br> Supported arguments: <br> - `from: {item: T; index: number}`: The dragged item. - `after: null \| {item: T; index: number}`: The item that the dragged item was dropped after. If dropped at the head of the collection, this argument will be `null`. - `filters`: Currently applied filters. Used in cases where your server holds a unique ordering per filtering. See the `dragAndDropCategories` prop. If the move is cancelled, the function returns a toast config object with a message. Otherwise, the function will return a null value. |
| `extensionMenuItems` | `ExtensionMenuItemsType` | No | - | @deprecated It doesn't need to be passed implicitly anymore. |
| `dragAndDropReorderModeToolbar` | `ReorderModeToolbarElement \| null` | No | - | Drag and drop reorder mode toolbar. This prop accepts a `ReorderModeToolbar` component.<br> The `ReorderModeToolbar` component accepts the following props:<br> + `learnMoreUrl`: [string] A URL in the toolbar.<br> + `reorderModeTitle`: [string] A title in the toolbar. |
| `customColumns` | `CustomColumnsElement \| null` | No | - | Adds functionality to allow visitors to create choose which columns to display and in what order. Accepts a [CustomColumns](./?path=/story/features-display--customcolumns) component. |
| `multiLevelSorting` | `MultiLevelSortingElement` | No | - | Adds functionality to allow visitors to sort multiple columns simultaneously. Accepts a [MultiLevelSorting](./?path=/story/features-sort-sortable-columns-multilevelsorting--multilevelsorting) component. |
| `primaryActionButton` | `PrimaryActionButtonElement` | No | - | Adds functionality for a primary action button in the toolbar. Accepts a [PrimaryActionButton](./?path=/story/features-actions-primary-actions--primary-action-button) component. |
| `secondaryActions` | `ToolbarSecondaryActionsElement` | No | - | Secondary buttons w/o PopoverMenu component to be rendered on the toolbar. |
| `moreActions` | `MoreActionsElement` | No | - | A [`MoreActions`](./?path=/story/features-actions-more-actions--more-actions) component to be rendered on the header. |
| `AddApplyFiltersButton` | `AddApplyFiltersButtonType` | No | - | Apply filter button implementation: `import { AddApplyFiltersButton } from '@wix/patterns';` <br> Add `Apply` button to the filters panel footer. Panel filters will be applied only after the button is clicked. |
| `internalScroll` | `boolean` | No | - | Indicates whether the table should have an [internal scroll](./?path=/story/features-display-internal-scroll--internal-scroll) instead of the default page scroll. |
| `showFieldTypeIcons` | `boolean` | No | `false` | When true, renders prefix icons for field types in column headers, filters, and the customize-columns panel. Each column and filter should have a `fieldType` property set so Cairo can render the matching icon. |
| `showTitleBar` | `boolean` | No | `true` | Indicates whether to show Table Title Bar or not. Note: if you pass `showTitleBar = false` title bar is not removed from the DOM. For better accessibility column titles should be defined as well. |
| `exportButton` | `ReactElement<any, string \| JSXElementConstructor<any>>` | No | - | A [`<ExportButton />`](./?path=/story/features-export--exportto) react element to be added to the toolbar |
| `importButton` | `ReactElement<any, string \| JSXElementConstructor<any>>` | No | - | A [`<ImportButton />`] react element to be added to the toolbar. |
| `exportModal` | `ReactElement<any, string \| JSXElementConstructor<any>>` | No | - | A [`<ExportModal />`](./?path=/story/features-export--exportto#CTA_is_out_of_the_table) react element to be rendered in table's context. |
| `importModal` | `ReactElement<any, string \| JSXElementConstructor<any>>` | No | - | A [`<ImportModal />`] react element to be rendered in table's context. |
| `dragAndDropCategories` | `(keyof F)[][] \| null` | No | - | By default, drag and drop works only without filters. To enable drag and drop with filters, pass an array of filters to this prop. The functionality will then work only for the specified filters, and to enable without filters, you must pass an empty array. For more information, see the [Drag and Drop Overview](//?path=/story/features-sort-drag-and-drop--overview). |
| `bulkActionToolbar` | `BulkActionToolbarRenderProp<T, F>` | No | - | A toolbar for performing bulk actions on multiple items.<br> <br> Supported parameters: <br> -`selectedValues`: [array] Items that are checked in the selection column. <br> -`uncheckedValues`: [array] Items that are unchecked in the selection column. <br> -`isSelectAll`: [bool] Whether **Select All** is checked. <br> -`openModal`: [func] Opens a modal that contains the component from `bulkActionModal` render prop. <br> -`clearSelection`: [func] Clears all selections. Call this after the action on the selected items finishes. <br> -`total`: [number] Total number of items in the server. <br> -`openConfirmModal`: [func] Opens a `<MessageModalLayout>` to confirm an action is about to be applied to the selected items. <br> -`query`: [object] Current paging, sorting, and filtering. Often used together with bulk actions, such as `updateAll`. <br> |
| `actionCell` | `ActionCell<T, F>` | No | - | Adds an action on the grid item. For example, a delete button to delete an item. Accepts an [`ActionCellProps`](https://www.docs.wixdesignsystem.com/?path=/story/components-lists-table--tableactioncell) object, or a function that returns an `ActionCellProps` object. |
| `renderAddItem` | `(() => ReactElement<AddItemProps, string \| JSXElementConstructor<any>>)` | No | - | A function that renders [`<AddItem>`](https://www.docs.wixdesignsystem.com/?path=/story/components-actions--additem&activeTab=Description&globals=backgrounds.value:!hex(F8F8F8);backgrounds.grid:false) after all cards in a gallery. <br><br> The `<AddItem>` card will not show when filters are applied unless the filter is defined with the persistent option. |
| `imagePlacement` | `"top" \| "side"` | No | - | Sets placement of a background image. |
| `skin` | `"standard" \| "neutral"` | No | - | @deprecated The table skin is fixed to `"neutral"` and any value passed here is ignored. This prop will be removed in a future release. |
| `maxSelection` | `number` | No | - | Limits the amount of rows a visitor can select. |
| `columns` | `TableColumn<T>[]` | Yes | - | Defines the columns of the table. Accepts an array of [`TableColumn`](./?path=/story/common-types--tablecolumn) objects. |
| `onRowClick` | `((item: T, index: number) => void)` | No | - | A callback method to be called on row click. Signature: `onRowClick(rowData, rowNum)`. To enable hover effect you should set this prop. |
| `hideBulkSelectionCheckbox` | `boolean` | No | - | Hides bulk selection checkbox in the table titlebar, If the [`MultiBulkActionToolbar`](./?path=/story/features-actions-bulk-actions--multibulkactiontoolbar) feature is enabled, this flag will have no effect. |
| `onSelectionChanged` | `OnSelectionChangedFn` | No | - | Defines a callback function which is called when selection happens. <br /> There are 3 types of selections: * `ALL` - bulk selection checkbox has been triggered to select all items * `SINGLE_TOGGLE` - a checkbox to select one item from the list has been triggered. The change object will also include an `id` prop with the unique item identifier and a `value` prop with the new boolean selection state of the item. * `NONE` - bulk selection has been triggered to unselect all items. |
| `onSelectionStarted` | `(() => void)` | No | - | Called when item selection triggered but not changed yet. |
| `showSelection` | `boolean` | No | `false` | Whether to show a checkbox column for selecting items. |
| `showRowNumbers` | `boolean` | No | `false` | When true and showSelection is enabled, displays row numbers in the selection column. The checkbox appears on hover or when the row is selected. |
| `bulkSelectionCheckboxRef` | `Ref<HTMLInputElement>` | No | - | A ref to the bulk selection checkbox in the table titlebar |
| `selectedIds` | `string[] \| number[]` | No | - | Defines an array of selected rows |
| `selectionDisabled` | `boolean \| SelectionDisabledFn<KeyedItem<T>>` | No | - | Specifies whether table row selection is restricted at a given moment. Can be defined as: * `bool` disables selection for all table rows * `function` that will be called for each row to check whether to disable selection or not depending on specified condition |
| `deselectRowsByDefault` | `boolean` | No | `false` | Controls bulk selection checkbox behaviour in indeterminate state. By default, first click on indeterminate state selects all items in the table. If set to `true`, first click will deselect all items instead. |
| `withWrapper` | `boolean` | No | `true` | When false then Table would not create a `<div/>` wrapper around it's children. Useful when using `<Table/>` to wrap a `<Page/>` component, in that case we use the `<Table/>` only as a context provider and it does not render anything to the DOM by itself. |
| `onSortClick` | `((colData: TableColumn<any>, colNum: number) => void)` | No | - | Defines a callback function which is called on column title click |
| `totalSelectableCount` | `number` | No | - | Specifies the total number of selectable items in the table (including items not loaded yet). When ‘Select all’ is triggered in infinite scroll tables, newly loaded items will be selected automatically. In this case, `SelectionContext` holds not-selected items rather than the selected ones. SelectionContext.infiniteBulkSelected is true and SelectionContext.selectedCount is the value of totalSelectableCount minus the count of unselected items. |
| `stickySelectionColumn` | `boolean` | No | - | Whether to add a sticky column. <br> Sticky columns allow you to display specific columns at all times while the visitor scrolls the table horizontally. |
| `dataExtension` | `(FC<DataExtensionOverrides> & DataExtensionObjectType) \| DataExtensionElement` | No | - | Data extension implementation: `import { DataExtension } from '@wix/patterns';` |
| `checkboxTooltipContent` | `((rowData: KeyedItem<T>) => string)` | No | - | A function that receives the item of the row and returns a string for tooltip content. |
| `bulkActionModal` | `BulkActionModalRenderProp<T, F>` | No | - | Opens a modal from the [`MultiBulkActionToolbar`](./?path=/story/features-actions-bulk-actions--multibulkactiontoolbar). Supported parameters: + `selectedValues`: Selected item values. + `uncheckedValues`: Unselected item values. + `isSelectAll`: [bool] Whether the **Select All** option is selected. + `closeModal`: Closes the modal. + `query`: [object] Instance of [ComputedQuery](./?path=/story/common-types--computedquery) that represents the query that resulted in an empty state. Representation of the current paging, sorting and filtering applied. Usually for using together with bulk action such as `updateAll` and `deleteAll`. |
| `actionCellWidth` | `string \| number` | No | - | Width of the column containing the `actionCell` component. |
| `actionCellProps` | `ActionCellPropsType<T>` | No | - | Extra columns props for the actions cell. |

## BI

### Events

 Event   |   Description   |
--------- | --------------- |
[144:153](https://bo.wix.com/data-tools/bi-catalog-app/event/144:153) | sent when a user choose to change the view of his components (list/ grid).


### Component load events
Event   |   Description   |
--------- | --------------- |
[144:110](https://bo.wix.com/data-tools/bi-catalog-app/event/144:110) | Sent when a Wix Patterns component starts loading
[144:111](https://bo.wix.com/data-tools/bi-catalog-app/event/144:111) | Sent when a Wix Patterns component is done loading


#### 🐪 Couldn't find what you need?
* Check our [BI Catalog](https://bo.wix.com/data-tools/bi-catalog-app?viewId=all-items-view&selectedColumns=src%2Cevid%2Cname%2Cowner%2Cproduct%2CuserType+false%2CdateUpdated%2CdateCreated+false%2CcreatedBy+false%2Cstatus&source=%5B%7B%22id%22%3A%22144%22%2C%22name%22%3A%22144+-+Cairo%22%7D%5D)
* Contact us on [#cairo-bi](https://wix.slack.com/archives/C03N53KURH9)


