Search code examples
reactjsmaterial-uidatagridmui-x

How to show by default unsorted icon on material ui?


I'm struggling to understand how I can by default show this icon, but not found anywhere.

I went to documentation and tried to show it by slot, but I get an error 'GridColumnUnsortedIcon is not defined'.

Documentation.

I found an issue on Github that is already resolved but didn't understand how to implement.

Issue


Solution

  • The default behavior for an unsorted column is to show the icon corresponding to what the sort will become after clicking it. Further, the default is for the icons in the column header to be hidden most of the time and to only show those icons while hovering over the column header.

    The first step is to customize the unsorted icon. In my example, I'm using SortByAlphaIcon. As with the icon customization example in the documentation, I wrap the icon in a thin layer (UnsortedIcon below) to control which props get passed through to the icon.

    import SortByAlphaIcon from "@mui/icons-material/SortByAlpha";
    
    export function UnsortedIcon({ className }) {
      return <SortByAlphaIcon className={className} />;
    }
    ...
    <DataGrid
            columns={columns}
            rows={rows}
            slots={{
              columnUnsortedIcon: UnsortedIcon
            }}
          />
    

    If you want that icon to show all the time (not just on hover), then you need to override the styles that are hiding it. You can see those style overrides specified via the sx prop in this working example:

    import * as React from "react";
    import { DataGrid } from "@mui/x-data-grid";
    import SortByAlphaIcon from "@mui/icons-material/SortByAlpha";
    
    const rows = [
      {
        id: 1,
        name: "MUI",
        stars: 28000
      },
      {
        id: 2,
        name: "DataGrid",
        stars: 15000
      }
    ];
    function UnsortedIcon({ className }) {
      return <SortByAlphaIcon className={className} />;
    }
    
    const columns = [
      { field: "name", width: 150 },
      { field: "stars", width: 150 }
    ];
    
    export default function CustomSortIcons() {
      return (
        <div style={{ height: 250, width: "100%" }}>
          <DataGrid
            sx={{
              "& .MuiDataGrid-columnHeader .MuiDataGrid-iconButtonContainer": {
                visibility: "visible",
                width: "auto"
              },
              "& .MuiDataGrid-columnHeader:not(.MuiDataGrid-columnHeader--sorted) .MuiDataGrid-sortIcon": {
                opacity: 0.5
              }
            }}
            columns={columns}
            rows={rows}
            slots={{
              columnUnsortedIcon: UnsortedIcon
            }}
          />
        </div>
      );
    }
    

    Edit always show unsorted icon