forked from petermoresi/react-download-link
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.mjs
71 lines (61 loc) · 1.66 KB
/
index.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import React, { Component } from "react";
import PropTypes from "prop-types";
class DownloadLink extends Component {
handleDownloadClick(event) {
function magicDownload(text, fileName) {
const blob = new Blob([text], {
type: "text/csv;charset=utf8;"
});
// create hidden link
const element = document.createElement("a");
document.body.appendChild(element);
element.setAttribute("href", window.URL.createObjectURL(blob));
element.setAttribute("download", fileName);
element.style.display = "";
element.click();
document.body.removeChild(element);
event.stopPropagation();
}
const fileType = event.target.innerText;
const text = this.props.exportFile(fileType);
if (text instanceof Promise) {
text.then(result => magicDownload(result, this.props.filename));
} else {
magicDownload(text, this.props.filename);
}
}
render() {
return React.createElement(
this.props.tagName || "a",
{
style: this.props.style,
className: this.props.className,
href: "javascript:void(0)",
onClick: this.handleDownloadClick.bind(this)
},
this.props.label
);
}
}
DownloadLink.defaultProps = {
filename: "file.txt",
label: "Save",
style: {
margin: "5px 5px 0px 0px",
textDecoration: "underline",
color: "blue",
cursor: "pointer"
},
exportFile: () => {}
};
DownloadLink.propTypes = {
filename: PropTypes.string,
label: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
PropTypes.object
]),
style: PropTypes.object,
exportFile: PropTypes.func
};
export default DownloadLink;