forked from canada-ca/tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExportButton.js
More file actions
40 lines (36 loc) · 1008 Bytes
/
Copy pathExportButton.js
File metadata and controls
40 lines (36 loc) · 1008 Bytes
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
import React from 'react'
import {Button} from '@chakra-ui/react'
import { arrayOf, object, string, func } from 'prop-types'
import { json2csvAsync } from 'json-2-csv'
import { Trans } from '@lingui/macro'
export function ExportButton({ jsonData, fileName, dataFunction, ...props }) {
const download = async () => {
try {
let data
if (jsonData) {
data = await json2csvAsync(jsonData)
}
else if (dataFunction) {
data = await dataFunction()
}
const a = document.createElement('a')
a.href = 'data:text/csv;charset=utf-8,' + encodeURI(data)
a.download = `${fileName}.csv`
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
} catch (err) {
console.log(err)
}
}
return (
<Button {...props} variant="primary" onClick={download}>
<Trans>Export to CSV</Trans>
</Button>
)
}
ExportButton.propTypes = {
jsonData: arrayOf(object),
fileName: string,
dataFunction: func,
}