6

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?

J. Hesters
  • 13,117
  • 31
  • 133
  • 249
  • If this is for production code you're probably best of using the FileSaver module, given the many ways manually downloading a file can go wrong across browsers: https://github.com/eligrey/FileSaver.js/ if you are totally against using a module, then if you google "how to download blobs with Javascript" you'll find a few posts, usually involving creating links and clicking them, then removing the links. Just be aware of cross-browser concerns. – Jayce444 May 12 '19 at 12:00
  • Possible duplicate of [How to create a file in memory for user to download, but not through server?](https://stackoverflow.com/questions/3665115/how-to-create-a-file-in-memory-for-user-to-download-but-not-through-server) – Endless Jun 19 '19 at 15:00

1 Answers1

12

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');
}
l-portet
  • 636
  • 7
  • 14