N
N
Nick Fisher2019-01-30 14:41:45
JavaScript
Nick Fisher, 2019-01-30 14:41:45

How to make a link to download a file in react?

Good afternoon. There is a completely trivial task that was solved by native js like this

const download = filename, text) => {
    let element = document.createElement('a');
    element.setAttribute('href', 'somelink' + text);
    element.setAttribute('download', filename);
    document.body.appendChild(element);
    element.click();
    document.body.removeChild(element);
  }

There was a task to fix it on IE11 (this is not about that) and I found out that the download attribute is not very friendly.
I decided to rewrite in react and everything stopped working even in chrome.
What am I doing wrong?
const download = (filename, text) => {
  return (
     <a href={'somelink' + text} download={filename} />
  )

I tried to write paths without a link directly - it does not help

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Taratin, 2019-01-30
@Taraflex

Regarding your first method
In addition to download, always add target="_blank" + server upload with title
https://developer.mozilla.org/en/docs/Web/HTTP/%D0...
Instead of element.click(); create an event through createEvent because just .click() is not particularly cross-browser
https://stackoverflow.com/a/902838
Regarding the second, it's generally nonsense. Just use the first one.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question