Home > Software design >  Is there a way to utilize React's `history.push()` to trigger a file download?
Is there a way to utilize React's `history.push()` to trigger a file download?

Time:06-11

Context

I'm trying to have a button trigger a download -- the <Button/> component within the codebase I'm working with does not support href, so I can't do something simple like href="/files/${id}.csv". I thought I could use something like the history() API to fetch a file, but it's appending .json to the end of my file and isn't working.

  • What am I doing wrong or misunderstanding about history?
  • If this isn't possible, what might be a better way to achieve my goal?

What I've Tried

I have the following code within a functional component:

handleCSVDownload = id => () => {
  const { history } = props;
  history.push(`/files/${id}.csv`);
}

const { fileId } = props;
<Button onClick={handleCSVDownload(fileId)}>Download File<Button/>

I would expect onClick to have the CSV download dialog appear.

However, this doesn't happen and I get a 404 w/ .json added to the URL:

GET http://localhost/files/1234.csv.json 404 (Not Found)
                                   ^^^^^

NOTE: Additionally, another odd thing is, if I hit "back" in my browser, I'll then be prompted for the file download, despite the URL not resolving onClick.

Question

Why is .json appended to my CSV link? Can someone help me better understand history under the hood in relation to why my code might not be working as expected? Any thoughts on a better solution?

CodePudding user response:

I don't know which library do you use for history. But I could suggest a maybe simple solution using window.open() function, it will trigger file downloading

handleCSVDownload = id => () => {

  window.open(`/files/${id}.csv`, "_blank");
}
  • Related