Search code examples
javascriptreactjsmui-x-data-grid

Can I download a specific record by clicking on a custom button in the MUI X-Data-grid?


I'm using MUI x-data-grid (community version) and want to download a record in CSV format by clicking on a custom button.. I know this can be achieved using the GridToolBar export option. But I want to trigger this on button click


Solution

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

    It has examples that match exactly what you need:

    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 (
        <GridToolbarContainer>
          <Button {...buttonBaseProps} onClick={() => handleExport()}>
            Export As CSV
          </Button>
        </GridToolbarContainer>
      );
    };
    

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