Search code examples
reactjscreate-react-apppapaparse

How to write data in a csv file within single-page-application(React JS )?


I want to write or overwrite data(or insert row) in a csv file within react-application(create-react-app) . My App.js file for now is -

import React, { Component} from 'react';

const csvData =[
  ['Ahmed', 'Tomi' , '[email protected]'] ,
  ['Raed', 'Labes' , '[email protected]'] ,
  ['Yezzi','Min l3b', '[email protected]']
];

export default class App extends Component {

    render() {
        return(
            <div>
            </div>
            );
    }

}

Here , I want to insert csvData in a csv file called data.csv within my react-application

my data.csv for now is :

Name,NickName,Email
Rahul B.,Rah,[email protected]
Abhinav K.,Abhi,[email protected]
Akshay G.,Aksh,[email protected]

where

Name,NickName,Email

are headers of my csv file .

I want my data.csv to look like -

Name,NickName,Email
Rahul B.,Rah,[email protected]
Abhinav K.,Abhi,[email protected]
Akshay G.,Aksh,[email protected]
Ahmed, Tomi , [email protected]
Raed, Labes , [email protected]
Yezzi,Min l3b,[email protected]

So how to update data.csv with my App component (React component) .

Thanks in advance .


Solution

  • You can use this library which was helpful to me

    https://www.npmjs.com/package/react-csv

    Please note this command will install the library in your project folder.

    npm i react-csv
    

    import {CSVLink, CSVDownload} from 'react-csv';
    
    const csvData =[
      ['firstname', 'lastname', 'email'] ,
      ['Ahmed', 'Tomi' , '[email protected]'] ,
      ['Raed', 'Labes' , '[email protected]'] ,
      ['Yezzi','Min l3b', '[email protected]']
    ];
    

    <CSVLink data={csvData} >Download me</CSVLink>
    // or
    <CSVDownload data={csvData} target="_blank" />