I'm using React to create a PWA (meaning it should ideally be usable on mobile and in the browser). I have a button in my drawer (burger menu) that should let the viewer download a CSV file.
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
// ...
<ListItem
button
onClick={handleExport}
className="drawer-export-contacts-button"
>
<ListItemIcon>
<ShareIcon />
</ListItemIcon>
<ListItemText primary={strings.exportContacts} />
</ListItem>
I have a function that prepares the CSV data as a Blob
but I can't figure out how to trigger the download.
function handleExport() {
const csv = convertContactsToCSV(contacts);
const csvData = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
// ...
}
How can you let the user download data?
You can use FileSaver, which is a great tool to manage files on client-side.
Your code should look like this:
import FileSaver from 'file-saver';
function handleExport() {
const csv = convertContactsToCSV(contacts);
const csvData = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
FileSaver.saveAs(csvData, 'data.csv');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With