Search code examples
reactjstypescriptmui-x-data-grid

React - Mui DataGrid - How to disable Menu in GridToolbarExport?


I need some help figuring out how to disable the menu in GridToolbarExport.

This is my MUI Data Grid

<DataGrid       
  localeText={{
    toolbarExport: "Export as CSV",
  }}    
  disableColumnMenu={true}    
  components={{
    Toolbar: CustomToolbar,
    NoResultsOverlay: GridNoResults,
  }}
  ....
/>

My CustomToolBar looks like this:

const CustomToolbar = (props: any) => {
  const currentDate = new Date();
  const formattedDate = currentDate.toISOString().slice(0, 10);
  const formattedTime = currentDate.toISOString().slice(11, 19);
  const fileName = `List-${formattedDate}-${formattedTime}.csv`;

  const csvOptions = {
    allColumns: true,
    fileName: fileName,
    delimiter: ";",
    utf8WithBom: true,
  };

  return (
    <div>
      <div style={{ marginRight: "auto" }}>
        <GridToolbarExport
           csvOptions={csvOptions}
           disableColumnSelector={true}
           disableColumnFilter={true}
           printOptions={{ disableToolbarButton: true }}
        />
      </div>
    </div>
  );
};

The "Export as CSV" button currently only displays the CSV export option because I disabled the print export. I was expecting the Save As dialog box to open directly when I clicked on the button. However, instead, a submenu labeled "Download as CSV" appears, and the save action only happens when I click this submenu. I would like the save action to be triggered when I click the main button itself.

Any help is appreciated.


Solution

  • Check out MUI's documentation on CSV Export: https://mui.com/x/react-data-grid/export/#customizing-the-rows-to-export

    You can create your own button with custom export functions. In your case, it would look something like this:

    const CustomToolbar = (props: any) => {
      const apiRef = useGridApiContext();
    
      const handleExport = (options?: GridCsvExportOptions) =>
        apiRef.current.exportDataAsCsv(options);
    
      const buttonBaseProps: ButtonProps = {
        color: "primary",
        size: "small",
        startIcon: <FileDownloadIcon />,
      };
    
      return (
        <div>
          <div style={{ marginRight: "auto" }}>
            <GridToolbarContainer>
              <Button {...buttonBaseProps} onClick={() => handleExport()}>
                Export As CSV
              </Button>
            </GridToolbarContainer>
          </div>
        </div>
      );
    };
    

    And you can pass in your desired export options into the handleExport function.