0

I have all the data fetched from backend and I need to save all the data as CSV on button click in reactJS app. So far solutions in js include appending an object and mock clicking on it. I do not need any third party library such as CSVLink because it requires a format that I think is unnecessary for my need and I will use nested objects and I am willing make complex code. So I'm stuck in this saving part mainly. I thought using axios and URL.createObjectURL on a blob object but that seems not a good idea. How can I do it?

My try code:

...
const testCSV = "H1, H2, H3, Hydrogen, Oxygen, Water"; //save it as .csv file

const data = [
    { firstname: "Ahmed", lastname: "Tomi", email: "[email protected]" },
    { firstname: "Raed", lastname: "Labes", email: "[email protected]" },
    { firstname: "Yezzi", lastname: "Min l3b", x: "[email protected]" },
];
    
const blob = new Blob([JSON.stringify(data)]);
const ahref = URL.createObjectURL(blob);

function TESTFunc() {
    console.log("Hello");
}
return (
    <Container fluid >
        
        {/* I do not want this
        <Button variant="secondary">
        <CSVLink data={data} headers={headers}>
            Download me
        </CSVLink>
        </Button>
        */}

        <Button variant="success" onClick={TESTFunc}></Button> {//download on this button click}
    </Container>
);
...

1 Answer 1

1
const downloadCSV = (csv, filename) => {
  const blob = new Blob([csv], { type: 'text/csv' });

  if (navigator && navigator.msSaveOrOpenBlob) {
    navigator.msSaveOrOpenBlob(blob, filename);
  } else {
    const dataURI = `data:text/csv;charset=utf-8,${csv}`;

    const URL = window.URL || window.webkitURL;
    const downloadURI =
      typeof URL.createObjectURL === 'undefined' ? dataURI : URL.createObjectURL(blob);

    let link = document.createElement('a');
    link.setAttribute('href', downloadURI);
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
};
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.