Examples › Custom row or cell attributes

Adding custom attributes to table rows or cells can be useful for testing purposes, for analytics, or for handling events the DataTable doesn’t expose a dedicated property for.

To add custom attributes to table rows, use the customRowAttributes property. It accepts a function that receives the current record and its index as arguments and returns an object whose properties are applied as attributes to the corresponding row.

Similarly, each column accepts a customCellAttributes property, which works the same way, but applies the returned attributes to the column’s cells.

Inspect the table below to see the attributes generated for each row and cell:

Name
City
State
Feest, Bogan and HerzogStromanportWY
Cummerata - KuhlmanSouth GateNH
Goyette IncDorthysideID
Runte IncMcAllenMA
Goldner, Rohan and LehnerNorth LouieWY
No records

Here is the code:

return (
  <DataTable
    withTableBorder
    columns={[
      { accessor: 'name' },
      { accessor: 'city', customCellAttributes: ({ city }) => ({ 'data-cy-city': city }) },
      { accessor: 'state', customCellAttributes: ({ state }) => ({ 'data-cy-state': state }) },
    ]}
    records={records}
    customRowAttributes={({ id, name }, recordIndex) => ({
      'data-cy-id': id,
      'data-cy-name': name,
      'data-cy-index': recordIndex,
    })}
  />
);

Handling middle-clicks

Since the returned object can also contain event handlers, here is how you could use the customRowAttributes property to handle middle-clicks on table rows:

Name
City
State
Feest, Bogan and HerzogStromanportWY
Cummerata - KuhlmanSouth GateNH
Goyette IncDorthysideID
Runte IncMcAllenMA
Goldner, Rohan and LehnerNorth LouieWY
No records

Here is the code:

return (
  <DataTable
    withTableBorder
    columns={[{ accessor: 'name' }, { accessor: 'city' }, { accessor: 'state' }]}
    records={records}
    customRowAttributes={({ name }) => ({
      onMouseDown: (e: React.MouseEvent) => {
        if (e.button === 1) {
          showNotification({ message: `Middle-click on row ${name}`, withBorder: true });
        }
      },
    })}
  />
);

Head over to the next example to discover more features.

Mantine DataTable is used and trusted by