Luiz Domingues
Luiz Domingues

Reputation: 369

How do I group by a value in a nested object in ReactJS material-table?

Let's say I have an array of people with a nested object company and I want to be able to group by company.name in the Material-Table.

const people = [ 
  {name: 'John', company: {name: 'Google'}},
  {name: 'Chad', company: {name: 'Google'}},
  {name: 'Mary', company: {name: 'StackOverflow'}
]

<MaterialTable
  data={people}
  columns=[
            {
              title: "Company", field: "company.name", grouping: true,
              render: rowData => rowData.company.name
            },
  ],
  options={grouping: true}
/>

The table sorts correctly by the company name, but if I try to group by column, it throws an error:

table-config.js is the location of the columns array

table-config.js:187 Uncaught TypeError: Cannot read property 'name' of undefined
at Object.render (table-config.js:187)
at MTableCell.getRenderValue (m-table-cell.js:94)
at MTableCell.render (m-table-cell.js:176)
at finishClassComponent (react-dom.development.js:18470)
at updateClassComponent (react-dom.development.js:18423)
at beginWork$1 (react-dom.development.js:20186)
at HTMLUnknownElement.callCallback (react-dom.development.js:336)
at Object.invokeGuardedCallbackDev (react-dom.development.js:385)
at invokeGuardedCallback (react-dom.development.js:440)
at beginWork$$1 (react-dom.development.js:25780)

How exactly do I make this work?

Thanks

Upvotes: 3

Views: 2877

Answers (1)

Renaldo Balaj
Renaldo Balaj

Reputation: 2440

You can modify the people array, and group by company

const people = [ 
  {name: 'John', company: {name: 'Google'}},
  {name: 'Chad', company: {name: 'Google'}},
  {name: 'Mary', company: {name: 'StackOverflow'}
].map((value)=> {
   value.company = value.company.name
   return value
})

Upvotes: 1

Related Questions