SCCCCC
SCCCCC

Reputation: 21

How do I fix these errrors when trying to create Material-UI DataGrid?

I'm getting the following errors when I try to create a Material-UI DataGrid:

Uncaught Error: MUI: The data grid component requires all rows to have a unique id property. A row was provided without id in the rows prop

And

Warning: Failed prop type: Invalid prop `rows[0]` of type `array` supplied to `ForwardRef`, expected `object`

Here is how I'm creating the grid:

<DataGrid
    columns={[
        {field: "id", headerName: "ID", width: 75, editable: false},
        {field: "number", headerName: "Number", width: 150, editable: false},
        {field: "serial", headerName: "Serial", width: 150, editable: false},
    ]}
    rows={response.data.map((item, index) =>[
        {
            id: index,
            number: item.number,
            serial: item.serial,
        },
    ])}
    pageSize={15}
    rowsPerPageOptions={[9]}
    checkboxSelection
    disableSelectionOnClick
/>

As you can see I do have an id field, and it's still complaining about it. This is also how the id is defined in the examples on Material-UI's website. What is wrong here?

Upvotes: 1

Views: 4620

Answers (2)

Neha
Neha

Reputation: 3650

If you have a unique key in the array you're providing, just add that to the rowID attribute.

<DataGrid getRowId={row => row.yourUniqueField}

If you don't have a unique key for each array element just append a uuid.

Upvotes: 1

Ren&#233; Link
Ren&#233; Link

Reputation: 51353

Yo map each item as an array of one item. You should use

rows={response.data.map((item, index) =>(
    {
        id: index,
        number: item.number,
        serial: item.serial,
    }
))}

You wrote

response.data.map((item, index) =>[
    {
        id: index,
        number: item.number,
        serial: item.serial,
    },
])

which maps the response.data to an array of arrays of one item.

[ [ {id, number, serial} ], [ {id, number, serial} ], ... ]

Thats why material ui states that the id is missing. What you want is

[ {id, number, serial}, {id, number, serial}, ... ]

Here is a codesandbox you can fiddle with.

Upvotes: 1

Related Questions