# Table

**Category:** Base Components/Collections/Table/Table

## Import

```tsx
import { Table, useTableCollection } from '@wix/patterns'
```

## Design

### Description

The `Table` component displays data in rows and columns, allowing you to organize information in an easy-to-scan format. This component extends the standard Wix Design System [`Table`](https://www.docs.wixdesignsystem.com/?path=/story/components-lists-table--table) to offer additional advanced features like infinite scroll, search, and filters.

#### Usage

1. Wrap your code in a `WixDesignSystemProvider` followed by a [`WixPatternsProvider`](./?path=/story/base-components-providers--wixpatternsprovider).
1. Wrap `Table` in a [`CollectionPage`](./?path=/story/base-components-pages-collection-page--collectionpage).
1. Create a [`TableState`](./?path=/story/base-components-collections-table-tablestate--tablestate) using [`useTableCollection()`](./?path=/story/base-components-collections-table-usetablecollection--usetablecollection).
1. Pass the `TableState` to the `state` prop.

```tsx
import { Table } from '@wix/patterns';
```

---

### Variations

### Basic table

A basic table. Contains a search bar in the table's toolbar by default. To remove the search bar from the table's toolbar, set the `collectionSearch` prop to `false`.

```tsx
import React from 'react';
import { CollectionPage } from '@wix/patterns/page';
import {
  CollectionEmptyState,
  Table,
  OffsetQuery,
  useTableCollection,
} from '@wix/patterns';
import { Avatar } from '@wix/design-system';
import { Edit } from '@wix/wix-ui-icons-common';
import { contacts } from '@wix/crm';

function BasicTable() {
  const tableState = useTableCollection<contacts.Contact>({
    queryName: 'contacts-Basic',
    itemName: (item) => `${item.info?.name?.first} ${item.info?.name?.last}`,
    fetchData: async (query: OffsetQuery) => {
      const { limit, offset, search } = query;
      let queryBuilder = contacts.queryContacts().limit(limit).skip(offset);

      if (search) {
        queryBuilder = queryBuilder.startsWith('info.name.first', search);
      }

      const { items = [], totalCount: total } = await queryBuilder.find();
      return {
        items,
        total,
      };
    },
  });

  return (
    <CollectionPage height="400px">
      <CollectionPage.Header title={{ text: 'Contacts' }} />
      <CollectionPage.Content>
        <Table
          state={tableState}
          columns={[
            {
              title: '',
              width: '50px',
              render: (contact) => (
                <Avatar
                  name={`${contact.info?.name?.first} ${contact.info?.name?.last}`}
                />
              ),
            },
            {
              title: 'Name',
              render: (contact) =>
                `${contact.info?.name?.first} ${contact.info?.name?.last}`,
              width: '300px',
            },
            {
              title: 'Last Activity',
              render: (contact) =>
                contact.lastActivity?.activityDate?.toLocaleString(),
            },
          ]}
          actionCell={() => ({
            secondaryActions: [
              {
                icon: <Edit />,
                text: 'Edit',
                onClick: () => {},
              },
            ],
          })}
        />
      </CollectionPage.Content>
    </CollectionPage>
  );
}
```

### Horizontal scroll

Enabling horizontal scrolling within rows.

```tsx
import React from 'react';
import { CollectionPage } from '@wix/patterns/page';
import { Table, OffsetQuery, useTableCollection } from '@wix/patterns';
import { Avatar, Text } from '@wix/design-system';
import { contacts } from '@wix/crm';

function HorizontalScrollTable() {
  const tableState = useTableCollection<contacts.Contact>({
    queryName: 'contacts-HorizontalScroll',
    itemName: (item) => `${item.info?.name?.first} ${item.info?.name?.last}`,
    fetchData: async (query: OffsetQuery) => {
      const { limit, offset, search } = query;

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

      if (search) {
        queryBuilder = queryBuilder.startsWith('info.name.first', search);
      }

      return queryBuilder.find().then(({ items = [], totalCount: total }) => {
        return {
          items,
          total,
        };
      });
    },
  });

  return (
    <CollectionPage height="400px">
      <CollectionPage.Header title={{ text: 'Contacts' }} />
      <CollectionPage.Content>
        <Table
          state={tableState}
          horizontalScroll // Add this line to enable horizontal scrolling
          columns={[
            {
              title: '',
              width: '50px',
              render: (contact) => (
                <Avatar
                  name={`${contact.info?.name?.first} ${contact.info?.name?.last}`}
                />
              ),
            },
            {
              title: 'Name',
              render: (contact) =>
                `${contact.info?.name?.first} ${contact.info?.name?.last}`,
              width: '250px',
            },
            {
              id: 'email',
              title: 'Email',
              width: '200px',
              render: (contact) => (
                <Text ellipsis>{contact.primaryInfo?.email}</Text>
              ),
            },
            {
              id: 'phone',
              title: 'Phone',
              width: '200px',
              render: (contact) => contact.primaryInfo?.phone,
            },
            {
              id: 'lastActivity',
              title: 'Last Activity',
              width: '200px',
              render: (contact) =>
                contact.lastActivity?.activityDate?.toLocaleString(),
            },
            {
              id: 'createdDate',
              title: 'Created Date',
              width: '200px',
              render: (contact) => contact._createdDate?.toLocaleString(),
            },
            {
              id: 'updatedDate',
              title: 'Updated Date',
              width: '200px',
              render: (contact) => contact._updatedDate?.toLocaleString(),
            },
          ]}
        />
      </CollectionPage.Content>
    </CollectionPage>
  );
}
```

### Filters

A table with filters. Use the `filters` prop to add filter capabilities to the table's toolbar.

```tsx
import React from 'react';
import { CollectionPage } from '@wix/patterns/page';
import {
  CollectionToolbarFilters,
  idNameArrayFilter,
  Table,
  MultiSelectCheckboxFilter,
  SingleSelectFilter,
  stringsArrayFilter,
  useCollection,
  Filter,
  useStaticListFilterCollection,
  useTableCollection,
} from '@wix/patterns';
import { Avatar } from '@wix/design-system';
import { contacts } from '@wix/crm';
import { subDays } from 'date-fns';

interface Duration {
  id: string;
  name: string;
  days: number | null;
}

type ContactsFilters = {
  level: Filter<string[]>;
  lastSeen: Filter<Duration[]>;
};

function ToolbarFiltersTable() {
  const tableState = useTableCollection<contacts.Contact, ContactsFilters>({
    queryName: 'contacts-ToolbarFilters',
    fetchData: (query) => {
      const { limit, offset, search, filters } = query;

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

      if (search) {
        queryBuilder = queryBuilder.startsWith('info.name.first', search);
      }

      if (filters.level) {
        queryBuilder = queryBuilder.in('info.jobTitle', filters.level);
      }

      const lastSeenDays = filters.lastSeen?.[0]?.days;
      if (lastSeenDays) {
        queryBuilder = queryBuilder.gt(
          'lastActivity.activityDate',
          subDays(new window.Date(), lastSeenDays),
        );
      }

      return queryBuilder.find().then(({ items = [], totalCount: total }) => {
        return {
          items,
          total,
        };
      });
    },
    itemName: (item) => `${item.info?.name?.first} ${item.info?.name?.last}`,
    filters: {
      level: stringsArrayFilter(),
      lastSeen: idNameArrayFilter(),
    },
  });

  const lastSeenCollection = useStaticListFilterCollection(
    tableState.collection.filters.lastSeen,
    [
      { id: 'w', name: 'Week', days: 7 },
      { id: 'm', name: 'Month', days: 30 },
      { id: 'y', name: 'Year', days: 365 },
      { id: 'o', name: 'Other', days: null },
    ],
  );

  const levelsCollection = useStaticListFilterCollection(
    tableState.collection.filters.level,
    [
      'Beginner',
      'Amateur',
      'Semi-Pro',
      'Professional',
      'World Class',
      'Legendary',
      'Ultimate',
    ],
  );

  return (
    <CollectionPage height="400px">
      <CollectionPage.Header title={{ text: 'Contacts' }} />
      <CollectionPage.Content>
        <Table
          state={tableState}
          columns={[
            {
              title: '',
              width: '50px',
              render: (contact) => (
                <Avatar
                  name={`${contact.info?.name?.first} ${contact.info?.name?.last}`}
                />
              ),
            },
            {
              title: 'Name',
              render: (contact) =>
                `${contact.info?.name?.first} ${contact.info?.name?.last}`,
              width: '250px',
            },
            {
              id: 'jobTitle',
              title: 'Job Title',
              render: (contact) => contact.info?.jobTitle,
            },
            {
              id: 'lastActivity',
              title: 'Last Activity',
              width: '200px',
              render: (contact) =>
                contact.lastActivity?.activityDate?.toLocaleString(),
            },
          ]}
          filters={
            <CollectionToolbarFilters
              inline={1}
              panelTitle="Filter your contacts"
            >
              <MultiSelectCheckboxFilter
                popoverProps={{ appendTo: 'window' }}
                placeholder="Select Level"
                accordionItemProps={{ label: 'Level' }}
                filter={tableState.collection.filters.level}
                collection={levelsCollection}
                renderItem={(level) => ({ title: level })}
              />

              <SingleSelectFilter
                filter={tableState.collection.filters.lastSeen}
                placeholder="Select Last Seen"
                accordionItemProps={{ label: 'Last Seen' }}
                collection={lastSeenCollection}
              />
            </CollectionToolbarFilters>
          }
        />
      </CollectionPage.Content>
    </CollectionPage>
  );
}
```

### Cursor Pagination

The default pagination is offset but you can change by providing cursor to `paginationMode` property.

```tsx
import React from 'react';
import { CollectionPage } from '@wix/patterns/page';
import {
  CollectionEmptyState,
  Table,
  useTableCollection,
  CursorQuery,
} from '@wix/patterns';
import { useHttpClient } from '@wix/yoshi-flow-bm';

interface User {
  id: string;
  name: string;
}

function CursorPaginationTable() {
  const httpClient = useHttpClient();

  const tableState = useTableCollection<User>({
    queryName: 'users-CursorPagination',
    paginationMode: 'cursor',
    fetchData: (query: CursorQuery) => {
      const { limit, cursor, search } = query;
      return httpClient
        .request<{ total: number; items: User[]; cursor?: string }>({
          url: '/api/users',
          data: {
            query: {
              limit,
              cursor,
              search,
            },
          },
        })
        .then(({ data: { items, total, cursor } }) => ({
          items,
          total,
          cursor,
        }));
    },
  });

  return (
    <CollectionPage height="400px">
      <CollectionPage.Header title={{ text: 'Users' }} />
      <CollectionPage.Content>
        <Table
          state={tableState}
          columns={[
            {
              title: 'Name',
              width: '250px',
              render: (user) => user.name,
            },
          ]}
          emptyState={<CollectionEmptyState />}
        />
      </CollectionPage.Content>
    </CollectionPage>
  );
}
```

### Header

A table with a header row. Set the `titleBarDisplay` prop to `false` to hide the table header row.

```tsx
import React from 'react';
import { CollectionPage } from '@wix/patterns/page';
import {
  CollectionEmptyState,
  Table,
  OffsetQuery,
  useCollection,
} from '@wix/patterns';
import { Avatar } from '@wix/design-system';
import { Edit } from '@wix/wix-ui-icons-common';
import { contacts } from '@wix/crm';

function HiddenHeader() {
  const collection = useCollection<contacts.Contact>({
    queryName: 'contacts-Basic',
    itemName: (item) => `${item.info?.name?.first} ${item.info?.name?.last}`,
    fetchData: (query: OffsetQuery) => {
      const { limit, offset, search } = query;

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

      if (search) {
        queryBuilder = queryBuilder.startsWith('info.name.first', search);
      }

      return queryBuilder.find().then(({ items = [], totalCount: total }) => {
        return {
          items,
          total,
        };
      });
    },
  });

  return (
    <CollectionPage height="400px">
      <CollectionPage.Header title={{ text: 'Contacts' }} />
      <CollectionPage.Content>
        <Table
          showTitleBar={false}
          state={collection}
          columns={[
            {
              title: '',
              width: '50px',
              render: (contact) => (
                <Avatar
                  name={`${contact.info?.name?.first} ${contact.info?.name?.last}`}
                />
              ),
            },
            {
              title: 'Name',
              render: (contact) =>
                `${contact.info?.name?.first} ${contact.info?.name?.last}`,
              width: '250px',
            },
            {
              id: 'jobTitle',
              title: 'Job Title',
              render: (contact) => contact.info?.jobTitle,
            },
            {
              id: 'lastActivity',
              title: 'Last Activity',
              width: '200px',
              render: (contact) =>
                contact.lastActivity?.activityDate?.toLocaleString(),
            },
          ]}
          emptyState={<CollectionEmptyState />}
          actionCell={(contact, index) => ({
            secondaryActions: [
              {
                icon: <Edit />,
                text: 'Edit',
                onClick: () => {},
              },
            ],
          })}
        />
      </CollectionPage.Content>
    </CollectionPage>
  );
}
```

### Table disabled rows

set `selectionDisabled` to disabled rows.

```tsx
import React from 'react';
import { CollectionPage } from '@wix/patterns/page';
import {
  Table,
  OffsetQuery,
  useTableCollection,
  MultiBulkActionToolbar,
} from '@wix/patterns';
import { Avatar } from '@wix/design-system';
import { Visible, Hidden } from '@wix/wix-ui-icons-common';
import { contacts } from '@wix/crm';

function SelectionDisabled() {
  const tableState = useTableCollection<contacts.Contact>({
    queryName: 'contacts-SelectionDisabled',
    itemName: (item) => `${item.info?.name?.first} ${item.info?.name?.last}`,
    fetchData: (query: OffsetQuery) => {
      const { limit, offset, search } = query;

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

      if (search) {
        queryBuilder = queryBuilder.startsWith('info.name.first', search);
      }

      return queryBuilder.find().then(({ items = [], totalCount: total }) => {
        return {
          items,
          total,
        };
      });
    },
  });

  const options = [
    { label: 'Visible', icon: <Visible /> },
    { label: 'Hidden', icon: <Hidden /> },
  ];

  const [selectedOption, setSelectedOption] = React.useState({
    label: 'Set Visibility',
    icon: <Visible />,
  });

  return (
    <CollectionPage height="400px">
      <CollectionPage.Header title={{ text: 'Contacts' }} />
      <CollectionPage.Content>
        <Table
          selectionDisabled={({ index }) => index % 2 === 0}
          checkboxTooltipContent={(rowData) => {
            const name = `${rowData.item.info?.name?.first} ${rowData.item.info?.name?.last}`;
            return `Selection disabled for ${name}`;
          }}
          bulkActionToolbar={() => {
            return (
              <MultiBulkActionToolbar
                primaryActionItems={[
                  {
                    dataHook: 'set-visibility',
                    label: selectedOption.label,
                    prefixIcon: selectedOption.icon,
                    subItems: options.map((el) => ({
                      prefixIcon: el.icon,
                      label: el.label,
                      onClick: () => setSelectedOption(el),
                    })),
                  },
                ]}
              />
            );
          }}
          state={tableState}
          columns={[
            {
              title: '',
              width: '50px',
              render: (contact) => (
                <Avatar
                  name={`${contact.info?.name?.first} ${contact.info?.name?.last}`}
                />
              ),
            },
            {
              title: 'Name',
              render: (contact) =>
                `${contact.info?.name?.first} ${contact.info?.name?.last}`,
              width: '300px',
            },
            {
              title: 'Created Date',
              render: (contact) => contact._createdDate?.toLocaleString(),
            },
          ]}
        />
      </CollectionPage.Content>
    </CollectionPage>
  );
}
```

---

### Virtual

The `TableVirtual` component is an extension of the `Table` component, designed to efficiently handle large datasets by utilizing virtualization. It provides smooth scrolling and rendering performance, especially when dealing with a large number of rows. The virtualization technique only renders the visible rows on the screen, making it highly efficient.

It is recommended to use the `rowHeight` prop when the row heights are consistent across the table, and the `estimatedRowHeight` prop when the row heights are variable. Providing the correct props helps to optimize the virtualized rendering process.

```tsx
import { Avatar } from '@wix/design-system';
import React from 'react';
import { Edit } from '@wix/wix-ui-icons-common';
import { CollectionPage } from '@wix/patterns/page';
import {
  CollectionEmptyState,
  OffsetQuery,
  useTableCollection,
  TableVirtual,
} from '@wix/patterns';
import { contacts } from '@wix/crm';

function Virtual() {
  const tableState = useTableCollection<contacts.Contact>({
    queryName: 'contacts-Virtual',
    itemName: (item) => `${item.info?.name?.first} ${item.info?.name?.last}`,
    fetchData: (query: OffsetQuery) => {
      const { limit, offset, search } = query;

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

      if (search) {
        queryBuilder = queryBuilder.startsWith('info.name.first', search);
      }

      return queryBuilder.find().then(({ items = [], totalCount: total }) => {
        return {
          items,
          total,
        };
      });
    },
  });

  return (
    <CollectionPage height="400px">
      <CollectionPage.Header title={{ text: 'Contacts' }} />
      <CollectionPage.Content>
        <TableVirtual
          state={tableState}
          rowHeight={78}
          columns={[
            {
              title: '',
              width: '50px',
              render: (contact) => (
                <Avatar
                  name={`${contact.info?.name?.first} ${contact.info?.name?.last}`}
                />
              ),
            },
            {
              title: 'Name',
              render: (contact) =>
                `${contact.info?.name?.first} ${contact.info?.name?.last}`,
              width: '300px',
            },
            {
              title: 'Created Date',
              render: (contact) => contact._createdDate?.toLocaleString(),
            },
          ]}
          emptyState={<CollectionEmptyState />}
          actionCell={(contact, index) => ({
            secondaryActions: [
              {
                icon: <Edit />,
                text: 'Edit',
                onClick: () => {},
              },
            ],
          })}
        />
      </CollectionPage.Content>
    </CollectionPage>
  );
}
```

---

### Fetch Total Async

Use the `fetchTotal` prop to retrieve the total number of items in the collection. This example demonstrates how to use the `fetchTotal` prop asynchronously.

```tsx
import React from 'react';
import { CollectionPage } from '@wix/patterns/page';
import {
  CollectionEmptyState,
  Table,
  useTableCollection,
  CursorQuery,
} from '@wix/patterns';
import { useHttpClient } from '@wix/yoshi-flow-bm';

interface User {
  id: string;
  name: string;
}

function FetchTotalTable() {
  const httpClient = useHttpClient();

  const tableState = useTableCollection<User>({
    queryName: 'users-CursorPagination',
    paginationMode: 'cursor',
    fetchTotal: async ({ limit, cursor, search }: CursorQuery) => {
      return new Promise((resolve, reject) => {
        window.setTimeout(() => {
          httpClient
            .request<{ total: number; items: User[]; cursor?: string }>({
              url: '/api/users',
              data: {
                query: {
                  limit,
                  cursor,
                  search,
                },
              },
            })
            .then(({ data: { total } }) => {
              resolve(total);
            })
            .catch(reject);
        }, 5000);
      });
    },
    fetchData: (query: CursorQuery) => {
      const { limit, cursor, search } = query;
      return httpClient
        .request<{ total: number; items: User[]; cursor?: string }>({
          url: '/api/users',
          data: {
            query: {
              limit,
              cursor,
              search,
            },
          },
        })
        .then(({ data: { items, cursor } }) => ({
          items,
          // total, // mimicking the total from the fetchTotal
          cursor,
        }));
    },
    fetchErrorMessage: () => 'Error fetching users',
  });

  return (
    <CollectionPage height="400px">
      <CollectionPage.Header title={{ text: 'Users' }} />
      <CollectionPage.Content>
        <Table
          state={tableState}
          columns={[
            {
              title: 'Name',
              width: '250px',
              render: (user) => user.name,
            },
          ]}
          emptyState={<CollectionEmptyState />}
        />
      </CollectionPage.Content>
    </CollectionPage>
  );
}
```

---

### Developer examples

### Using Ambassador

If you have a crud package from ambassador you can use our [useAmbassadorCollection](./?path=/story/common-hooks--useambassadorcollection) hook instead using the default [useCollection](./?path=/story/common-hooks--usecollection).

```tsx
import React from 'react';
import { CollectionPage } from '@wix/patterns/page';
import {
  CollectionEmptyState,
  Table,
  useAmbassadorCollection,
} from '@wix/patterns';
import * as ambassador from '@wix/ambassador-ecom-v1-order/crud/http';

function UseAmbassador() {
  const collection = useAmbassadorCollection({
    ambassador,
    itemName: (t) => t.number!,
    itemKey: (t) => t.id!,
  });

  return (
    <CollectionPage height="400px">
      <CollectionPage.Header title={{ text: 'Orders' }} />
      <CollectionPage.Content>
        <Table
          state={collection}
          columns={[
            {
              id: 'number',
              width: '30px',
              title: 'Number',
              sortable: true,
              render: (t) => t.number,
            },
            {
              id: 'paymentStatus',
              width: '50px',
              title: 'Payment Status',
              sortable: true,
              render: (t) => t.paymentStatus,
            },
            {
              id: 'fulfillmentStatus',
              width: '50px',
              title: 'Fulfillment Status',
              sortable: true,
              render: (t) => t.fulfillmentStatus,
            },
            {
              id: 'createdDate',
              width: '40px',
              title: 'Created Date',
              sortable: true,
              render: (t) => t.createdDate?.toLocaleDateString(),
            },
            {
              id: 'updatedDate',
              width: '40px',
              title: 'Updated Date',
              sortable: true,
              render: (t) => t.updatedDate?.toLocaleDateString(),
            },
            {
              id: 'buyerNote',
              width: '50px',
              title: 'Buyer Note',
              sortable: true,
              render: (t) => t.buyerNote,
            },
          ]}
          emptyState={<CollectionEmptyState />}
        />
      </CollectionPage.Content>
    </CollectionPage>
  );
}
```

### Using with External Data Source

This example demonstrates how to use the `fetchData` API when data already exists from an external source. In this specific case, we used `useRef` to store the data outside the table's scope, but this approach can be applied to any external source. The data can be saved in a context, propagated as a prop, or managed through any other solution that doesn't involve using httpClient directly to fetch the data.

 Note: Ensure that you use the query filter parameters, such as search and limit, to filter the data correctly.

```tsx
import React from 'react';
import { CollectionPage } from '@wix/patterns/page';
import { Table, OffsetQuery, useTableCollection } from '@wix/patterns';

interface Contact {
  id: string;
  name: string;
}

function UseExternalDataSource() {
  const loadDataFromServer: () => Promise<Contact[]> = async () => {
    return new Promise((resolve) => {
      window.setTimeout(
        () =>
          resolve([
            { id: '1', name: 'Alice Johnson' },
            { id: '2', name: 'Bob Smith' },
            { id: '3', name: 'Carol Davis' },
            { id: '4', name: 'David Martinez' },
            { id: '5', name: 'Emma Wilson' },
            { id: '6', name: 'Frank Taylor' },
            { id: '7', name: 'Grace Lee' },
            { id: '8', name: 'Henry White' },
            { id: '9', name: 'Ivy Harris' },
            { id: '10', name: 'Jack Brown' },
          ]),
        1000,
      );
    });
  };

  const dataRef = React.useRef<Promise<Contact[]>>(loadDataFromServer());

  const tableState = useTableCollection<Contact>({
    queryName: 'contacts-external-data',
    itemKey: (item) => item.id as string,
    itemName: (item) => item.name as string,
    fetchData: async (query: OffsetQuery) => {
      const { limit, offset, search } = query;
      const all = await dataRef.current; // wait for external source to be resolved
      let filtered = all; // initially assigned to all data

      // filter by search value if exists
      if (search && search.trim() !== '') {
        console.log('filtered', filtered);
        filtered = filtered.filter((c) =>
          (c.name as string).toLowerCase().includes(search.toLowerCase()),
        ); // filter by search value
      }

      // filter by given limit
      filtered = filtered.slice(offset, offset + limit);

      return {
        items: filtered,
        total: filtered.length,
      };
    },
    fetchErrorMessage: ({ err }) => String(err),
  });

  return (
    <CollectionPage height="400px">
      <CollectionPage.Header title={{ text: 'Contacts' }} />
      <CollectionPage.Content>
        <Table
          state={tableState}
          columns={[
            {
              title: 'Name',
              width: '250px',
              render: (contact) => contact.name,
            },
          ]}
        />
      </CollectionPage.Content>
    </CollectionPage>
  );
}
```

## API

### Extends

[TableProps](https://www.docs.wixdesignsystem.com/?path=/story/components-lists-table--table)

### Props

| Prop | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `state` | `CollectionState<T, F> \| TableState<T, F>` | Yes | - | A state instance created using the [`useTableCollection()`](./?path=/story/base-components-collections-table-usetablecollection--usetablecollection) hook, responsible for managing the data displayed in the table. |
| `sections` | `TableSectionsProp<T>` | No | - | Configuration for rendering table sections. When provided, the table will render with section headers that group related rows together |
| `columns` | `TableColumn<T>[]` | Yes | - | Defines the columns of the table. Accepts an array of [`TableColumn`](./?path=/story/common-types--tablecolumn) objects. |
| `showSelection` | `boolean` | No | `false` | Whether to show a checkbox column for selecting items. |
| `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. |
| `exportButton` | `ReactElement<any, string \| JSXElementConstructor<any>>` | No | - | A [`<ExportButton />`](./?path=/story/features-export--exportto) react element to be added to the toolbar. |
| `dragAndDrop` | `TableDragAndDropType` | 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). |
| `dataExtension` | `(FC<DataExtensionOverrides> & DataExtensionObjectType) \| DataExtensionElement` | No | - | Data extension implementation: `import { DataExtension } from '@wix/patterns';` |
| `fieldsSource` | `FieldsSourceProvider` | No | - | A fields source (e.g. `dataExtensionTableSource(...)`) whose fields become columns and whose field management wires into the table. Schema sources attach via the `@wix/patterns/schema` collection hooks instead. |
| `tags` | `TagsElement<T, F>` | No | - | Enables tags feature. In this element you can pass the configuration |
| `checkboxTooltipContent` | `((rowData: KeyedItem<T>) => string)` | No | - | A function that receives the item of the row and returns a string for tooltip content. |
| `bulkActionToolbar` | `BulkActionToolbarRenderProp<T, F>` | No | - | Render a custom toolbar when more than 1 item is selected.<br> The function accepts the following parameters * `selectedValues`: The items that were checked via the selection column * `uncheckedValues`: The items that were unchecked via the selection column * `allSelected`: Indicates whether the "Select All" checkbox is checked * `openModal`: Opens the modal that contains the component from `bulkActionModal` render prop * `clearSelection`: Clears all existing selection, call this after the action on the selected items was done * `total`: Total items in the server (taken from [`fetchData`](./?path=/story/common-hooks--usecollection) return value). * `openConfirmModal`: Opens a `<MessageModalLayout/>` to confirm an action about to be applied on the selected items. * `query`: ComputedQuery<F> - Representation of the current paging, sorting & filtering applied. Usually for using together with bulk action such as `updateAll` and `deleteAll` > When passed, enables `showSelection` by default. |
| `showAddFieldButton` | `boolean` | No | - | When true, wraps every column header with the AddField hover popover. The "+" button is revealed when the consumer hovers a column header and triggers either the schema's `addField` or the data-extension's custom fields modal. Off by default. |
| `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`. |
| `dataHook` | `string` | No | - | Applies a data-hook HTML attribute to be used in the tests |
| `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. |
| `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. |
| `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. |
| `maxSelection` | `number` | No | - | Limits the amount of rows a visitor can select. |
| `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. |
| `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). |
| `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. |
| `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. |
| `rowStatus` | `((row: KeyedItem<T>, rowNum: number) => TableRowStatusValue \| null)` | No | - | When provided, renders a fixed-width status slot per row to the right of the selection/row-number column. The callback returns a `{ status, messages }` config for rows that need a status indicator, or `null`/`undefined` for an empty but width-reserved slot — the slot never collapses. Only `error` and `warning` statuses are supported; the slot is exclusively for those two indicator kinds, rendered via the WDS `<StatusIndicator/>`. |
| `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. |
| `actionCell` | `ActionCell<T, F>` | No | - | Use this property to add an action at the end of each row. For example, a delete button to delete a table item. Accepts an [`ActionCellProps`](./?path=/story/features-actions-action-cell--actioncellprops) object, or a function that returns an `ActionCellProps` object. |
| `actionCellWidth` | `string \| number` | No | - | Width of the column containing the `actionCell` component. |
| `actionCellProps` | `ActionCellPropsType<T>` | No | - | Extra columns props for the actions cell. |

## Accessibility

### Description

## What we did
In this component we added a Live Region which announces the results which are rendered on the screen visually.

## Why is it important
Screen reader users, which have a severe visual impairment need to be notified when there is a change in the page layout or there is some error or status messages that appear. In some cases, in order not to interfere with the users current position on the page, the focus should be kept in place and the status should be announced (in case of search, tabs or adding an item from the collection header). In other cases, specifically if the button on which the user clicked disappears or becomes disabled, both techniques of focus management and live region should be used in parallel (in case of filter, or adding/removing an item from the collection).

Due to the fact that this all happens behind the scenes you can experience it only with a screen reader on in this video:


## What is included in the component?
Announcements of the total number of results which were found after performing a search, after applying a filter, when navigating between tabs and when changing the view in the dropdown.


## Testkit

### Extends

[TableTestkit](https://www.docs.wixdesignsystem.com/?activeTab=Testkit&path=%2Fstory%2Fcomponents-api-components--table)

