'export data as csv in react

I'm trying to export data as a csv in a react app without a library. My code looks like so:

 const download = () => {
    const dummyData = 'rahul,delhi,accountsdept\n';
    const csvContent = `data:text/csv;charset=utf-8,${dummyData}`;
    const encodedURI = encodeURI(csvContent);
    window.open(encodedURI);
}

And then I have a button with this download function as an onclick.

      <button onClick={download}>
        Generate Vehicle Offer Prices
      </button>

This is supposed to work in vanilla javascript, is there a reason it doesn't work in react?

Here's a sandbox with the code not working in react sandbox

Here's a link with it working in vanilla js vanilla



Solution 1:[1]

You can use the NPM library: https://www.npmjs.com/package/react-csv

Example

import {CSVLink, CSVDownload} from 'react-csv';

const csvData =[
  ['rahul', 'delhi', 'accountsdept']  
];
<CSVLink data={csvData} >Download me</CSVLink>

OR

<CSVDownload data={csvData} target="_blank" />

Solution 2:[2]

It is working actually, look here:

import "./styles.css";

export default function App() {
  const download = () => {
    const dummyData = "rahul,delhi,accountsdept\n";
    const csvContent = `data:text/csv;charset=utf-8,${dummyData}`;
    const encodedURI = encodeURI(csvContent);
    window.open(encodedURI);
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button onClick={download}>Generate Vehicle Offer Prices</button>
    </div>
  );
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ajay Gupta
Solution 2 MWO