1

I am creating a DataGrid where I want to show the values of ready_by and name that you can see in this picture:

Json of the data

In the code, I have configured it in this way: (focus on the last two)

const columns = [
    {
      field: 'id',
      headerName: "ID",
      minWidth: 50,
      type:"number",
      align:'left',
      hide:'true'
    },
    {
      field: 'customer',
      headerName: 'Customer',
      valueGetter: ({ value }) => value.email,
      width: 250,
    },
    {
      field: 'paid',
      headerName: 'Customer has paid?',
      width: 250,
    },
    {
      field: 'total',
      headerName: 'Cost',
      width: 150,
    },
    {
      field: 'details',
      headerName: 'Ready By',
      type: 'datetime',
      valueGetter: ({ value }) => value.ready_by && new Date(value.ready_by),
      width: 250,
    },
    {
      field: 'details',
      headerName: 'Name',
      valueGetter: ({ value }) => value[0].name,
      width: 250,
    },
  ];

The problem is that when I render the page only one of them shows up and that's because I repeat the field value. So I want to ask you how to resolve this:

Page with the Datagrid

3ndless_____
  • 154
  • 1
  • 11
Miquel Bars
  • 47
  • 1
  • 5
  • from the docs "field is the only required property since it's the column identifier." i guess you have to change field to be unique. https://mui.com/components/data-grid/columns/ – noobprogrammer Mar 30 '22 at 16:16
  • How can I do that? I don't see the propertie "unique" in the column documentation. – Miquel Bars Mar 30 '22 at 16:25

1 Answers1

2

Yes, that is correct. The "field" is a column identifier and must be unique.

Here's my solution:

Assumption: Here data means the array you're feeding to the rows prop for the <DataGrid/> MUI component.

const columns = React.useMemo(
     () => [
       ..., // all the other elements

  
       // No changes needed here since this is the first occurrence of 'details'
       {
         field: 'details',
         headerName: 'Ready By',
         type: 'datetime',
         valueGetter: ({ value }) => value.ready_by && new Date(value.ready_by),
         width: 250,
       },

        // Here we're basically searching for the item of interest since we do get `id` as a param arg.
       {
         field: 'details2',
         headerName: 'Name',
         valueGetter: ({ id }) => {
           const item = data.find(item => item.id === id);
           return item.name;
         },
         width: 250,
       },

     ],
    [data]
  )
Kushal
  • 71
  • 4