Cloudscape Design System
  • Get started
  • Foundation
  • Components
  • Patterns
  • Demos
  • GitHub 
Cloudscape Design System
  • Get started
  • Foundation
  • Components
  • Patterns
  • Demos
  • GitHub 
  • About
  • Guides
    • Introduction
    • Get started for designers
    • Get started for developers
  • Resources
    • Design resources
  • Integration
    • Using Cloudscape components
    • Global styles
  • Development guides
    • Collection hooks package
    • Content security policy (CSP)
    • Responsive development
    • State management
    • Z-index
  • Testing
    • Introduction to testing
    • Testing frameworks integration
    • Testing core classes
  1. Cloudscape Design System
    • Get started
    • Development guides: Collection hooks package

    Collection hooks package

    Use the Cloudscape collection hooks package to handle data operations in collection components.

      On this page

      • Overview
      • Install the package
      • Using with React
      • API

      Overview

      Cloudscape provides table and cards components to display collections of resources. These components display static datasets. Operations on these datasets (such as filtering, sorting, and pagination) should happen outside of these components.

      Client-side collections

      The @cloudscape-design/collection-hooks package provides utilities to handle filtering, sorting, or pagination operations when the full dataset describing the collection can be fetched on the client side, without requiring further asynchronous calls. This use case is called client-side collection.

      Server-side collections

      If your dataset has to be fetched asynchronously upon filtering, sorting, and pagination operations, don’t use the @cloudscape-design/collection-hooks package. Instead, implement the fetching, filtering, selection, pagination, and sorting yourself. This use case is called server-side collection.

      Install the package

      This package is published to NPM as @cloudscape-design/collection-hooks .

      For more information, see the package installation guide.

      Using with React

      This package exports the useCollection React hook . It takes the original collection items and a configuration, and returns filtered, sorted, and paginated content, according to your configuration.

      Code example

      Example below uses text filtering. Check out the official demo that uses property filtering feature of the collection hooks.

      Preview

      Instances (25)

       
      ID
      Availability zone
      State
       O4DMYB22MWEYROBVNSRANus-east-1cHealthy
       S4JE6P56MI4XBCMD63GQPus-east-1aHealthy
       7U59ZZLQYGXZFHTKZF7UIus-east-1dHealthy
       LF2QRGQR73UA8I4HOJXGPus-east-1bUnhealthy
       8WYHUA2A03V71YQMM5VYNus-east-1aHealthy
       PJVCIGWWP24XF6168QDR9us-east-1cHealthy
       DLBTSDMY30151I1B3Q77Bus-east-1eHealthy
       EEIX26WFY6YA56R2BER2Eus-east-1bHealthy
       8JMC1H9LIKCKGCXS6FT3Yus-east-1cHealthy
       KPG0CDOTQRF830MWRDIA5us-east-1dHealthy

      Code

      The following code uses React and JSX syntax .

      import React, { useState } from 'react';
      import { useCollection } from '@cloudscape-design/collection-hooks';
      import {
        Box,
        Button,
        CollectionPreferences,
        Header,
        Pagination,
        Table,
        TextFilter,
      } from '@cloudscape-design/components';
      import allItems from './data';
      import { columnDefinitions, getMatchesCountText, paginationLabels, collectionPreferencesProps } from './table-config';
      
      function EmptyState({ title, subtitle, action }) {
        return (
          <Box textAlign="center" color="inherit">
            <Box variant="strong" textAlign="center" color="inherit">
              {title}
            </Box>
            <Box variant="p" padding={{ bottom: 's' }} color="inherit">
              {subtitle}
            </Box>
            {action}
          </Box>
        );
      }
      
      export default function CollectionHooksTable() {
        const [preferences, setPreferences] = useState({ pageSize: 10, visibleContent: ['id', 'availabilityZone', 'state'] });
        const { items, actions, filteredItemsCount, collectionProps, filterProps, paginationProps } = useCollection(
          allItems,
          {
            filtering: {
              empty: (
                <EmptyState
                  title="No instances"
                  subtitle="No instances to display."
                  action={<Button>Create instance</Button>}
                />
              ),
              noMatch: (
                <EmptyState
                  title="No matches"
                  subtitle="We can’t find a match."
                  action={<Button onClick={() => actions.setFiltering('')}>Clear filter</Button>}
                />
              ),
            },
            pagination: { pageSize: preferences.pageSize },
            sorting: {},
            selection: {},
          }
        );
        const { selectedItems } = collectionProps;
        return (
          <Table
            {...collectionProps}
            selectionType="multi"
            header={
              <Header
                counter={selectedItems.length ? `(${selectedItems.length}/${allItems.length})` : `(${allItems.length})`}
              >
                Instances
              </Header>
            }
            columnDefinitions={columnDefinitions}
            visibleColumns={preferences.visibleContent}
            items={items}
            pagination={<Pagination {...paginationProps} ariaLabels={paginationLabels} />}
            filter={
              <TextFilter
                {...filterProps}
                countText={getMatchesCountText(filteredItemsCount)}
                filteringAriaLabel="Filter instances"
              />
            }
            preferences={
              <CollectionPreferences
                {...collectionPreferencesProps}
                preferences={preferences}
                onConfirm={({ detail }) => setPreferences(detail)}
              />
            }
          />
        );
      }
      

      Using custom operator matchers

      If you want to override the default filtering logic, use a match function on the extended operator notation:

      const { items, propertyFilterProps, ... } = useCollection({
        propertyFiltering: {
          filteringProperties: [
            // Using custom matcher to support searching with a comma-separated list
            {
              key: 'status',
              operators: [
                { operator: '=', match: (itemValue, tokenValue) => tokenValue.split(',').includes(itemValue) },
                { operator: '!=', match: (itemValue, tokenValue) => !tokenValue.split(',').includes(itemValue) },
              ],
              ...
            },
            // Using predefined date matcher
            {
              key: 'launchDate',
              operators: [
                { operator: '=', match: 'date' },
                { operator: '!=', match: 'date' },
                { operator: '<', match: 'date' },
                { operator: '<=', match: 'date' },
                { operator: '>', match: 'date' },
                { operator: '>=', match: 'date' },
              ],
              ...
            },
            // Using predefined datetime matcher
            {
              key: 'lastEventAt',
              operators: [
                { operator: '=', match: 'datetime' },
                { operator: '!=', match: 'datetime' },
                { operator: '<', match: 'datetime' },
                { operator: '<=', match: 'datetime' },
              ],
              ...
            },
          ]
        }
      });
      

      Note that overrides are done per operator.

      Intercepting event listeners

      If you want to define a custom behavior upon user actions, ensure you always call the method created by the collection hook:

      const { ..., paginationProps } = useCollection(...);
          
      return (
        <Table
          ...
          pagination={
            <Pagination
              {...paginationProps}
              onChange={event => {
                myCustomFunction(event);
                paginationProps.onChange(event);
              }}
            />
          }
        />
      );
      

      API

      useCollection(allItems: Array, configuration: Configuration): Result
      

      Configuration

      Name
      Type
      Description
      filtering
      Object

      Filtering configuration. If you want to activate filtering with default settings, provide an empty object.

      filteringFunction
      (item: T, text: string, fields?: string[]) => boolean

      Custom function to filter items. The default value is a function that loops through all items keys (unless fields property is provided, see below), converts all values to strings, and matches them against current filteringText.

      fields
      string[]

      Array of keys within the item object whose values are taken into account by the default filteringFunction.

      defaultFilteringText
      string

      Initial filtering value on the first render.

      empty
      React.ReactNode

      Content to display in the table/cards empty slot when there are no items initially provided.

      noMatch
      React.ReactNode

      Content to display in the table/cards empty slot when filtering returns no matched items.

      propertyFiltering
      Object

      Configuration for property filtering.

      filteringProperties
      readonly PropertyFilterProperty[]

      Array of properties by which the data set is going to be filtered. Individual items have following properties:

      • key [string]: The identifier of this property. Refer to a property name in type T of the data item to enable built-in filtering.

      • groupValuesLabel [string]: Localized string to display for the 'Values' group label for a specific property. For example: EC2 instance values.

      • propertyLabel [string]: A human-readable string for the property.

      • operators [ReadonlyArray<PropertyFilterOperator | PropertyFilterOperatorExtended>, optional]: A list of all operators supported by this property. The equals operator should always be supported, even if you omit it in the list. Operators can be extended to accept additional properties. Include match to define an alternative filtering logic.

      • group [string, optional]: Optional identifier of a custom group that this filtering option is assigned to. Use to create additional groups below the default one. Make sure to also define labels for the group in the customGroupsText property. Notice that only one level of options nesting is supported.