Search code examples
reactjscsvrowexport-to-csvshow

how to show csv file data in table at reactjs


i want to show csv data to table only specific column (1st and 2nd column) but header name have space and when show data error having.Please can u tell me how to solve that error.... Thank you

want to show like that enter image description here

My source code is below

test.csv

Test Data1,Test Data2,Test data3

AA,BB,CC

App.js

import React from "react";
import "./style.css";
import Papa from "papaparse";

export default function App() {
  const [rows, setRows] = React.useState(null);
  React.useEffect(() => {
    Papa.parse("/test.csv", {
      download: true,
      header: true,
      complete: data => {
        console.log(data.data);
        setRows(data);
      }
    });
  }, []);

  return (
    <div>
      <table>
        <tr>{rows?.meta.fields.map(column => <th>{column}</th>)}</tr>
        {rows?.data.map(row => {
          return (
            <tr>
              <td>{row.Test Data1}</td>
              <td>{row.Test Data2}</td>
              <td>{row.Test Data3}</td>
            </tr>
          );
        })}
      </table>
    </div>
  );
}

console enter image description here

error enter image description here


Solution

  • In your CSV file, change the column names to testData1, testData2, ...

    In your code, change the attributes accordingly:

    <tr>
      <td>{row.testData1}</td>
      <td>{row.testData2}</td>
      <td>{row.testData3}</td>
    </tr>
    

    ... or, keep the column names as they are and change the code to:

    <tr>
      <td>{row['Test Data1']}</td>
      ...
    </tr>