Search code examples
javascriptreactjsmui

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"));

Solution

  • 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.