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
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" />
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>
);
}