I have a react app and I want to download a file via a predefined link as soon as I click on download bottom. The issue is that it starts downloading without clicking on download bottom whenever I refresh.
here is how I defined bottom:
<div className="file-list">
<ul className="m-0 p-0 px-3 pt-1">
{filesList.map((value) => (
<li key={value} className="file-item p-2 mb-2">
<div className="is-flex is-align-items-center">
<img className="fileIcon mr-3" src={FileIcon} />
<span className="filename is-flex">{value}</span>
<div className="is-flex is-flex-direction-column is-align-items-center">
<Icon
onClick={downloadSampleCsvFile(value)}
path={mdiDownload}
title="Download"
size={0.79}
color="#0a85c7"
/>
here is how I defined downloadSampleCsvFile(value):
const downloadSampleCsvFile = (v) => {
axios({
url: 'https://raw.githubusercontent.com/anubhav-goel/react-download-file-axios/main/sampleFiles/csv-sample.csv', //your url
method: 'GET',
responseType: 'blob', // important
}).then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'csv-sample.csv'); //or any other extension
document.body.appendChild(link);
link.click();
});
};
CodePudding user response:
Your file gets downloaded automatically because you're invoking download function in onChange
event listener . Simply change it to this
onClick={() => downloadSampleCsvFile(value)}
CodePudding user response:
The function is running as soon as the element is rendered since you are calling it directly. A better way to do it is
()=>downloadSampleCsvFile(value)