Search code examples
reactjsapimaterial-uireact-tablemui-datatable

Mui datatables support nested array from API?


I want to use MUI datatable with the following nested array currently working like this as expected:

  {this.state.posts.map((posts,index) => (
      <>
      {posts.map((item, j) => (
      <tr key={j}>
        <td>{item.id}</td>
        <td>{item.date}</td>
      </tr>
        )
      )}
      </>
  ))}

I have my MUIDatatables set up with the correct columns:

const columns = ["ID", "Date"];

const options = {
  filterType: 'checkbox',
  enableNestedDataAccess: "."
};

And then my MUI table component would presumably work as something like this for the data:

<MUIDataTable
  title={"Employee List"}
  data={this.state.posts.map((posts,index) => (
    {posts.map((item,j) => {
        return [
            item.id,
            item.date,
        ]
    })}
  ))}
  columns={columns}
  options={options}
/>

But this syntax doesnt seem to be working for the data part (or supported at all?). Any ideas how to achieve this with data coming directly from the API in a nested array or how to approach this for a solution?


Solution

  • I think that given your source data, you give MUIDataTable data prop an array with 3 dimensions, instead of 2 expected.

    To fix that, you could try to flatten the source arrays to have a normal collection of objects, and then iterate over it.

    Example:

    <MUIDataTable
      title={"Employee List"}
      data={this.state.posts.flat().map(item => {
            return [
                item.id,
                item.date,
            ]
        })}
      ))}
      columns={columns}
      options={options}
    />
    

    Would that work?