Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of objects with mui-datatables

Question for someone who uses mui-datatables. It works with data as array of strings, however fails to load array of objects with this error:

bundle.js:126379 Uncaught (in promise) TypeError: e.map is not a function

import MUIDataTable from "mui-datatables";

class App extends React.Component {

render() {

const columns = ["Name", "Title", "Location", "Age", "Salary"];

const data = [
  {name: "Gabby George", title: "Business Analyst", location: "Minneapolis", age: 30, salary: "$100,000"}      
];

const options = {
  filterType: 'dropdown',
  responsive: 'stacked'
};

return (
  <MUIDataTable 
    title={"ACME Employee list"} 
    data={data} 
    columns={columns} 
    options={options} 
  />
);

//return <div>a</div>;

  }

}

ReactDOM.render(<App />, document.getElementById("root"));
like image 770
lentyai Avatar asked Mar 30 '18 21:03

lentyai


3 Answers

For what it's worth, I've basically been mapping my array of objects into simple value arrays inline, like so:

const docs = [{"name": "Doc 1", "type": "PDF"}, {"name": "Doc 2", "type": "JPG"}];

<MUIDataTable
    title="Documents"
    data={docs.map(item => {
        return [
            item.name,
            item.type,
        ]
    })}
    columns={Object.keys(docs)}
/>

You could integrate this into a wrapper component of some kind, but it's pretty simple to add this in a one-off situation.

Note: MUI Datatables won't render if the data array is empty, so I often add my columns manually and also check data for length before mapping, otherwise return an array like [[" "]]. This at least results in a blank table being rendered.

like image 70
Andy Z Avatar answered Nov 13 '22 03:11

Andy Z


mui-datatables indeed supports arrays of objects. In order to use an array of objects, the object property must be specified in the columns array as such:

const columns = [
  { label: "Name", name: "name" },
  { label: "Title", name: "title" }, 
  { label: "Location", name: "location" }, 
  { label: "Age", name: "age" }, 
  { label: "Salary", name: "salary" }
];

const data = [
  {name: "Gabby George", title: "Business Analyst", location: "Minneapolis", age: 30, salary: "$100,000"}      
];

const options = {
  filterType: 'dropdown',
  responsive: 'stacked'
};

return (
  <MUIDataTable 
    title={"ACME Employee list"} 
    data={data} 
    columns={columns} 
    options={options} 
  />
);
like image 22
Ace Avatar answered Nov 13 '22 04:11

Ace


For the ones who stumble upon this question. It turned out that I'm not missing anything, and 'mui-datatables' only support array of arrays - no support for array of objects in plans. And that's too bad - I believe that components as such should work with data the way it's returned by API... Oh, well I guess will have to make my own wrapper component to take care of it.

like image 2
lentyai Avatar answered Nov 13 '22 05:11

lentyai