How to let the user download data (CSV) in React?
Asked Answered
K

1

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?

Kynthia answered 12/5, 2019 at 11:50 Comment(2)
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: 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.Cressy
Possible duplicate of How to create a file in memory for user to download, but not through server?Tactical
L
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');
}
Lima answered 12/5, 2019 at 16:1 Comment(2)
is there a way to not use any extra package such as file-saver?Tough
Sure, but you will have to handle the specific old browsers cases. That's where the library is really useful.Lima

© 2022 - 2024 — McMap. All rights reserved.