How can I add onClick functionality to IndexTable rows?

Hi all,

I trying to add the onClick functionality to the rows in an IndexTable but having no success.

The index table has the bulk select ability as well.

In short, I’m trying to replicate the behaviour you can see on the Shopify Orders page for a store.

Basically, if you click on anywhere on the row, the order details page appears. However, if you click on the checkbox, the bulk select options appear.

What I have is if you click on where in the row, the bulk select option appears.

I’d like to replicate the behaviour in the orders page.

Below is my IndexTable code and rowMarkup.

<IndexTable
    resourceName={resourceName}
    promotedBulkActions={promotedBulkActions}
    itemCount={packages.length}
    selectedItemsCount={
        allResourcesSelected ? 'All' : selectedResources.length
    }
    onSelectionChange={handleSelectionChange}
    headings={[
        {title: 'Package Name'},
        {title: 'Height'},
        {title: 'Width'},
        {title: 'Depth'},
        {title: 'Max Weight (g)'},
    ]}
>
    {rowMarkup}
</IndexTable>

const rowMarkup = packages.map(
    ({id, packageName, height, width, depth, maxWeight}, index) => (
        <IndexTable.Row
            id={id}
            key={id}
            selected={selectedResources.includes(id)}
            position={index}
        >
            <IndexTable.Cell>
                <TextStyle variation="strong">{packageName}</TextStyle>
            </IndexTable.Cell>
            <IndexTable.Cell>{height}</IndexTable.Cell>
            <IndexTable.Cell>{width}</IndexTable.Cell>
            <IndexTable.Cell>{depth}</IndexTable.Cell>
            <IndexTable.Cell>{maxWeight}</IndexTable.Cell>
            <IndexTable.Cell><Button onClick={() => alert("Edited")}>
                Edit
            </Button></IndexTable.Cell>
        </IndexTable.Row>
    ),
);

Much appreciate your help.

1 Like

Hey there!

This is a bit of a tricky one since Polaris doesn’t have it documented. If you pass an HTML element in your Index.Row that has “data-primary-link”, it’ll change the behaviour of the click event to navigate instead. You can also pass onNavigation to the Index.Row.

You’ll still have some work to do to provide the correct URL and handle navigation. Here’s an example to get you going in the right direction:

const rowMarkup = packages.map(
  ({id, packageName, height, width, depth, maxWeight, url}, index) => (
    
  ),
);

I’ve always found it useful to dive into the source code of Polaris React. Here’s a link to the snippet of code you’re working with: IndexTable.Row source code.

1 Like

As of 12/10/2023, sadly, your link to the snippet of code you’re working with: IndexTable.Row source code. is dead.

Here is the up-to-date link: https://github.com/Shopify/polaris/blob/main/polaris-react/src/components/IndexTable/components/Row/Row.tsx

1 Like