reactjsmaterial-uimui-x-data-grid

How can I implement a condition in the renderCell method of a MUI X Data Grid GridColDef component?


I'm using the MUI X Data Grid component and want to render the content of one column based on some conditions of the data.

How can I basically implement a conditional in the renderCell method?

const columns: GridColDef[] = [

      { field: 'offer_status',
          headerName: 'Status',
          flex: 1,
          width: 50,
          renderCell: (params) => ({
            if (params.value == 'is_sent')
                return <div>Sent</div>
          }
      )},

This doesn't work - I assume due to the syntax (unexpected token).


Solution

  • This is a working example of how to do a conditional inside a renderCell:

    renderCell: params => {
      if (params.row.programId === 1) {
        return <div>Graduação</div>;
      }
      return <div>Pós-Graduação</div>;
    }
    

    This is a piece of code contained in one project that uses ESLint and Prettier code formatter.

    enter image description here

    As you can see in the image above, I did a similar code to that you have shown in this post, after doing it, this error appeared:

    Expected to return a value at the end of method 'renderCell'

    This means that you must return some value to renderCell method, in your code if the conditional is not satisfied the renderCell will never receive a returned value and that's what causes the error. Also, another thing that you should do is write params instead of (params), because it's a single function argument, this means that the parentheses around are not necessary.