React Native Tutorial to Create or Export CSV Files and Download it Locally in Browser Using react-native-fetch-blob Library & TypeScript Full Project For Beginners

 

 

You can use react-native-fetch-blob to write to the device’s file system. (I was wondering this too!)

We start by converting an array of values to a string. If our values are separated by , commas and our rows are separated by \n newlines, then our string is csv. We can take that string, write it to a file with a .csv file extension, and voila we have a .csv file.

here’s code that does just this:

 

 

import RNFetchBlob from 'react-native-fetch-blob';

const values = [
  ['build', '2017-11-05T05:40:35.515Z'],
  ['deploy', '2017-11-05T05:42:04.810Z']
];

// construct csvString
const headerString = 'event,timestamp\n';
const rowString = values.map(d => `${d[0]},${d[1]}\n`).join('');
const csvString = `${headerString}${rowString}`;

// write the current list of answers to a local csv file
const pathToWrite = `${RNFetchBlob.fs.dirs.DownloadDir}/data.csv`;
console.log('pathToWrite', pathToWrite);
// pathToWrite /storage/emulated/0/Download/data.csv
RNFetchBlob.fs
  .writeFile(pathToWrite, csvString, 'utf8')
  .then(() => {
    console.log(`wrote file ${pathToWrite}`);
    // wrote file /storage/emulated/0/Download/data.csv
  })
  .catch(error => console.error(error));

Leave a Reply