Search code examples
javascriptreactjsmui-datatable

A column in MUI Datatable do not hide or show based on a state true or false condition


I'm trying to display or hide a column in an MUI datable based on a condition of a state. I put ane example here which works CodeSandBox

In this example, if you tweak line 14 between true and false, you will see a column is displayed or hide. Distance column.

This same behavior I'm trying to reach in my code but it does not work and I don't know why: Link to code

I added a link as I have no idea what wrong but I tried the as same way I did in CodeSandBox:

The data in codeSandbox is a representation similar to what is here an OBJ containing two key/values

   {
         lat: 40.7110316
​
         lng: -74.0013216
    }

My data and state and function isDisplay()

    const [usingLocation, setLocation] = useState(null);
    
    const isDisplay = () => {
    if (usingLocation !== null) return true;
    else return false;
  };

My columns

const columns = useMemo(
    () => [
      'Id',
      {
        name: 'Distance',
        options: {
          display: isDisplay(),
          filter: false,
          customBodyRender: value => {
            return !value ? 'N/A' : `${value} ${DISTANCE_MEASURE}`;
          },
        },
      },
    ],
    [sites, site],
  );

In my situation, the Distance column never shows even though the usingLocation is true.

I really don't get what I'm doing wrong.


Solution

  • You are using display: isDisplay() in the memoized columns variable. But isDisplay is not declared in the dependency array, only site and sites are. This causes to column not to re-render when isDisplay's return value changes.

    So it should be:

    const columns = useMemo(
        () => [
          'Id',
          {
            name: 'Distance',
            options: {
              display: isDisplay(),
              filter: false,
              customBodyRender: value => {
                return !value ? 'N/A' : `${value} ${DISTANCE_MEASURE}`;
              },
            },
          },
        ],
        [sites, site, isDisplay],
      );
    

    Though, personally, I don't see a reason to memoize columns.