Search code examples
node.jsreactjsreact-nativecsvpapaparse

Displaying local CSV data in a table in React


I'm new to react and only have an entry level understanding of coding but need to use it for a project.

I'm trying to display data from a local csv file in a simple HTML table that can then be searched by a user on the page. So far I've only been able to find tutorials that require users to upload their own CSV first but I just need to have the data on the screen.

I appreciate that this is probably a really simple question but its all new to me and I just can't seem to find a solution that works.

This code is from one of the tutorials I've followed and returns the result I need but only when the user uploads the csv first.

    import React, {useState, useCallback} from 'react'
import {useDropzone} from 'react-dropzone'
import Papa from 'papaparse';
import './App.css';


 export default function MyDropzone () {
  const onDrop = useCallback(acceptedFiles => {
    if (acceptedFiles.length) {
  parseFile(acceptedFiles[0]);
}
  }, []);

  const {getRootProps, getInputProps, isDragActive, isDragAccept, isDragReject} = useDropzone({onDrop, accept: 'text/csv'})

  const [parsedCsvData, setParsedCsvData] = useState([]);

  const parseFile = file => {
Papa.parse(file, {
    header: true,
    complete: results => {
      setParsedCsvData(results.data)
    },
  });
};

return (
  <div className="Archive">
    <div
      {...getRootProps({
        className: `dropzone
        ${isDragAccept && 'dropzoneAccept'}
        ${isDragReject && 'dropzoneReject'}`,
      })}
    >
      <input {...getInputProps()} />
      {isDragActive ? (
        <p>Drop the files here ...</p>
      ) : (
        <p>Drag 'n' drop some files here, or click to select files</p>
      )}
    </div>
    <table className="ArchiveTable">
      <thead>
        <tr>
          <th>Kanji</th>
          <th>Reading</th>
          <th>English</th>
        </tr>
      </thead>
      <tbody>
        {parsedCsvData &&
          parsedCsvData.map((parsedData, index) => (
            <tr key={index}>
              <td>{parsedData.Name}</td>
              <td>{parsedData.Address}</td>
              <td>{parsedData.Postcode}</td>
              <td>{parsedData.Issue}</td>
              <td>{parsedData.Date}</td>
              <td>{parsedData.Score}</td>
            </tr>
          ))}
      </tbody>
    </table>
  </div>
);
}

Solution

  • Try this:

    change the url inside fetch to the location to your csv file in this line const response = await fetch("/data/nodes.csv"); .

    import React, { useState, useEffect } from "react";
    import "./App.css";
    import Papa from 'papaparse';
    
    export default function MyDropzone() {
        const [parsedCsvData, setParsedCsvData] = useState([]);
    
        useEffect(() => {
            async function getData() {
                const response = await fetch("/data/nodes.csv");
                const reader = response.body.getReader();
                const result = await reader.read(); // raw array
                const decoder = new TextDecoder("utf-8");
                const csv = decoder.decode(result.value); // the csv text
                const results = Papa.parse(csv, { header: true }); // object with { data, errors, meta }
                const rows = results.data; // array of objects
                setParsedCsvData(rows);
            }
            getData();
        }, []);
    
        return (
            <div className="Archive">
                <table className="ArchiveTable">
                    <thead>
                        <tr>
                            <th>Kanji</th>
                            <th>Reading</th>
                            <th>English</th>
                        </tr>
                    </thead>
                    <tbody>
                        {parsedCsvData &&
                            parsedCsvData.map((parsedData, index) => (
                                <tr key={index}>
                                    <td>{parsedData.Name}</td>
                                    <td>{parsedData.Address}</td>
                                    <td>{parsedData.Postcode}</td>
                                    <td>{parsedData.Issue}</td>
                                    <td>{parsedData.Date}</td>
                                    <td>{parsedData.Score}</td>
                                </tr>
                            ))}
                    </tbody>
                </table>
            </div>
        );
    }