Welcome folks today in this blog post we will be exporting mock json
data to csv
file and download it inside the browser in react.js using the react-json-to-csv
library. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new react.js
app using the below command as shown below
npx create-react-app sampleapp
cd sampleapp
npm i react-json-to-csv
And after that you will see the below directory
structure of the react.js project as shown below
And now we need to edit the App.js
file and copy paste the following code which is shown below
App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
import './App.css'; import React, { createRef } from "react"; import CsvDownloadButton from 'react-json-to-csv' function App() { let mockData = [ { name:'John', country:'New Zealand' }, { name:'John', country:'New Zealand' }, { name:'John', country:'New Zealand' }, { name:'John', country:'New Zealand' } ] return ( <div> <CsvDownloadButton headers={['customName,customCountry']} filename='file.csv' data={mockData}/> </div> ); } export default App; |
As you can see we are importing the module
at the top and then we are passing the mock
json data and then we are passing the custom
filename of the csv file and then you can even pass the headers
and columns of the csv file.