javascriptreactjscsvpapaparse

Using papaparse to parse a CSV file with Javascript in a React app


I have a CSV file in the same directory as my React app that I am trying to read with Javascript. I am using Papaparse to parse the CSV file.

Here is my code:

Papa.parse("./headlines.csv", {
    download: true,
    complete: function(results, file) {
    console.log("Parsing complete:", results, file);
  }
})

My issue is that when I try to parse the file, all that gets returned is the HTML code for the index.html file in my React app.


Solution

  • Well according to PapaParser Docs, you need to pass in a js File Object or a CSV String.

    // file is a File object obtained from the DOM.
    // config is a config object which contains a callback.
    // Doesn't return anything. Results are provided asynchronously to a callback function.
    
    Papa.parse(file, config)
    

    JS: Using Async/Await

    const csv = await fetch('/headlines.csv').then( res => res.text() );
    
    Papa.parse( csv, {
        download: true,
        complete: function(results, file) {
            console.log("Parsing complete:", results, file);
        }
    });
    

    JS: Using Promises

    fetch('/headlines.csv')
        .then( res => res.text() )
        .then( csv => {
            Papa.parse( csv, {
                download: true,
                complete: function(results, file) {
                    console.log("Parsing complete:", results, file);
                }
            });
        });