简体   繁体   中英

react-export-excel download from onClick handler

I am using "react-export-excel" lib to export json to excel.

This does work when clicking the button, but the process I want is:

  • Add an onClick to the button without downloading the file straight away

  • In the onClick event, show a loader

  • Then download the file

  • Then hide the loader when the file has downloaded

     <ExcelFile filename="Companies" element={<Button variant="dark-green" onClick={downloadCompanies}>Download</Button>}> <ExcelSheet data={companyExport.length > 0 && companyExport} name="Companies"> <ExcelColumn label="Company Name" value="name"/> <ExcelColumn label="Address" value="address"/> <ExcelColumn label="Town" value="town"/> <ExcelColumn label="Postcode" value="postcode"/> <ExcelColumn label="Phone" value="telephone"/> <ExcelColumn label="Website" value="website"/> </ExcelSheet>
    const downloadCompanies = e => {
        setDownloadingLoader(true)
        // Download file now
    }

    // Some event listener when the file has downloaded to hide loader

Does anyone know it's possible to achieve this with this library? Any help would be greatly appreciated.

not sure if you are still looking for an answer; I needed to achieve the same thing; what I think I am going to do, is having my own button other than the Download button listed above; onclick event of that button I would trigger the click event for the button attached with ExcelFile. You would obviously change

<ExcelFile
     filename="Companies"
     element={<Button variant="dark-green" onClick={downloadCompanies}>Download</Button>}>
     <ExcelSheet data={companyExport.length > 0 && companyExport} name="Companies">

to

<ExcelFile
     filename="Companies"
     element={<Button innerRef={this.buttonRef}></Button>}>
     <ExcelSheet data={companyExport.length > 0 && companyExport} name="Companies">

Then you can have your own button

<Button variant="dark-green" onClick={downloadCompanies}>Download</Button>

And in your downloadCompanies method you'll do following

if (this.buttonRef.current !== null) {
                this.buttonRef.current!.click();
            }

This is the best I think we can do with this component, let me know if you ended up with a better way or decided to use another component, thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM