Search code examples
arraysreactjsobjectimport-from-excel

React push data into object of arrays


How do I get imported data from importFile.js into dataTable.js?

https://github.com/Romson/CSV-file-uploader/blob/master/src/components/importFile.js https://github.com/Romson/CSV-file-uploader/blob/master/src/components/dataTable.js

Tried this function to change nested arrays in imported data from importFile.js into a object of arrays.

const newArray = [data].map(
  ([firstName, lastName, issueCount, dateOfBirth]) => ({
    firstName,
    lastName,
    issueCount,
    dateOfBirth
  })
);

Then a push into dataTable.js with:

data.rows.push(newArray);

What is the correct way to do this in React?

Expected result is to get the imported data to show in this table:

https://csv-file-uploader.herokuapp.com/


Solution

  • What you want to do is make DataTable component a child of Reader component. You need the array of object from Reader component for the rows property of datatable in DataTable component. As you said you are a beginner so better start from react hooks as it is easy.

    Reader component

    import React, {useState} from "react";
    import CSVReader from "react-csv-reader";
    import DatatablePage from "./dataTable";
    import "../index.css";
    
    const Reader = () =>  { 
     const [data, setData] = useState([]);
    return (
      <div className="container">
        <CSVReader
          cssClass="react-csv-input"
          label="Upload a new CSV file"
          onFileLoaded={(data) => setData(data)}
        />
        <DatatablePage uploadedData={data} />
      </div>
    );
    }
    
    export default Reader;
    

    DatatablePage component

    import React from "react";
    import { MDBDataTable } from "mdbreact";
    
    const DatatablePage = ({uploadedData}) => {
      const data = {
        columns: [
          {
            label: "First Name",
            field: "name",
            sort: "asc",
            width: 150
          },
          {
            label: "Last Name",
            field: "surname",
            sort: "asc",
            width: 270
          },
          {
            label: "Issue count",
            field: "issuecount",
            sort: "asc",
            width: 200
          },
          {
            label: "Date of birth",
            field: "dateofbirth",
            sort: "asc",
            width: 100
          }
        ],
        rows: []
      };
    // we append the passed props in the rows. read about spread operator if unaware of it.
    
    const datatableProps = {...data, rows: uploadedData}; 
      return <MDBDataTable striped bordered hover uploadedData={uploadedData} data={datatableProps} />;
    };
    
    export default DatatablePage;
    

    We are using react hooks to create a state variable named data and a setter for it. Then we pass this state variable to the child component which can render it.