colado
colado

Reputation: 327

Is there a way to add an icon when sort direction is null on Material UI's DataGrid headers?

Material UI's DataGrid's API shows how to add a sort icon when the direction is ascending and another one when the sort direction is descending. These default to the arrow up and arrow down icons and can easily be changed through props. My design requires to also have an icon when the sorting direction is null (i.e., the user hasn't clicked on that column header yet but the up-and-down arrows indicate that the column is sortable).

I have tried a couple of solutions but I'm not satisfied with any of them. I tried using renderHeader inside the ColDef to implement the icons when SortModel changes but it doesn't look good enough, plus the DataGrid layout gets messed up for some reason when SortModel is changed.

Is there a better way to simply add a sortable icon next to the header titles when no sorting direction is defined?

Upvotes: 1

Views: 3826

Answers (1)

NearHuscarl
NearHuscarl

Reputation: 81390

Material-UI DataGrid does not have an option to set the icon in no-sort state. To do that, you need to get your hands dirty.

I tried using renderHeader inside the ColDef to implement the icons when SortModel changes but it doesn't look good enough

In order to replicate the built-in sort icon, you need to know which components get rendered in the column header when in sorting mode. Having a look at the DataGrid source code, you can see that:

  • In GridColumnHeaderItem: If you don't provide renderHeader, it will render GridColumnHeaderTitle instead. So we need to use that component to render the header.

  • In GridColumnHeaderSortIcon: This component is used to render the sort icon, the icon is wrapped inside an IconButton with a small size that itself is wrapped inside a container. Make sure to copy that code when you render your own header icon.

Putting it together, we'll have something like below:

import { GridColumnHeaderTitle } from "@material-ui/x-grid";
{
  field: "firstName",
  headerName: "First name",
  width: 130,
  renderHeader: (params) => {
    const { field, api, colDef } = params;
    const sort = api.state.sorting.sortModel.filter(
      (s) => s.field === field
    )?.[0]?.sort;
    const isSorting = Boolean(sort);

    return (
      <>
        <GridColumnHeaderTitle
          label={colDef.headerName || colDef.field}
          description={colDef.description}
          columnWidth={colDef.width}
        />
        {!isSorting && (
          <div className="MuiDataGrid-iconButtonContainer">
            <IconButton size="small">
              <ClearIcon className="MuiDataGrid-sortIcon" />
            </IconButton>
          </div>
        )}
      </>
    );
  }
},

Live Demo

Edit 66899204/is-there-a-way-to-add-an-icon-when-sort-direction-is-null-on-material-uis-datag

Upvotes: 4

Related Questions