Search code examples
javascriptreactjsdatatablesjsxmui-datatable

react mui-datatables, can't export only selected rows


I'm using "mui-datatables": "^4.2.2",

I wonder if this library is customizable enough to work with, because currently I just want to export the rows of tables that are selected.

enter image description here

I used the default download button of the library and also I added a custom button to allow the download of only selected table rows

const options = {
    ...  // other options
     onDownload: (buildHead, buildBody, columns, rows) => {
      console.log(rows); //  <-------- can't get only selected rows
    },
    customToolbarSelect: (selectedRows, displayData, setSelectedRows) => {
      return (
        <Box mr={4}>
          <Fab
            variant="extended"
            size="small"
            color="primary"
            aria-label="add"
            onClick={() => console.log(displayData)} // <--- can't get selected rows
          >
            <FileDownloadRounded />
            Exporter
          </Fab>
        </Box>
      );
    },

}

I used a customToolbarSelect and i tried to customize onDownload but i can't get only selected rows.

How can i correctly download only selected rows ?

Thank you !


Solution

  • The code below demonstrates how you can retrieve records corresponding to selected rows in the toolbar context:

    const options = {
    ...  // other options
     onDownload: (buildHead, buildBody, columns, rows) => {
      console.log(rows); //  <-------- can't get only selected rows
    },
    customToolbarSelect: (selectedRows, displayData, setSelectedRows) => {
    
      const handleClick = () => {
         const recordsToDownload = selectedRows?.data?.map(
             ({ index }) => displayData[index]
         ).map(
             ({ data }) => data
         );
    
        console.log('recordsToDownload', recordsToDownload);
      };
    
      return (
        <Box mr={4}>
          <Fab
            variant="extended"
            size="small"
            color="primary"
            aria-label="add"
            onClick={handleClick}
          >
            <FileDownloadRounded />
            Exporter
          </Fab>
        </Box>
      );
    },
    

    Then you can use the createCSVDownload utility function to trigger CSV file download process: (https://github.com/gregnb/mui-datatables/blob/25e16b22cb146619d671fc2db8504aa98deddd0f/src/utils.js#L129)

    The same function is used in the default toolbar: https://github.com/gregnb/mui-datatables/blob/master/src/components/TableToolbar.js