Search code examples
javascriptreactjsmaterial-uishow-hide

How to hide/show column based on if statement using Material-ui?


I have the following code, and I want to hide or show the TableCell based on if statement, how do I do that?

I am using MATERIAL-UI : https://material-ui.com/

  <TableBody>
                {Object.entries(servicesCode).map(([key, value]) => (
                  servicesValueTotal[key] = ((servicesValue[key] + servicesTaxe[key])),
                  <TableRow key={servicesCode[key]}>
                    <TableCell component="th" scope="row">
                      {key}
                    </TableCell>
                    <TableCell align="center" >{servicesCode[key]}</TableCell>
                    <TableCell align="center">{servicesValue[key]}</TableCell>
                    <TableCell align="center">{servicesTaxe[key]}</TableCell>
                    <TableCell align="center">{servicesValueTotal[key]}</TableCell>
                    <TableCell align="center">{servicesTec[key]}</TableCell>
                    <TableCell align="center">{servicesClient[key]}</TableCell>
                    <TableCell align="center">{servicesStatus[key]}</TableCell>
                  </TableRow>
                ))}
              </TableBody>

Solution

  • Why not use the feature called conditional rendering?

    {condition && <Component />}, for example {condition && <TableCell align="center" >{servicesCode[key]}</TableCell>}

    Note: As You are using a table to display data, it should have fixed number of th tags - table headings, thus removing table cells completely might be a bad solution.

    You could also leave the table cell empty based on conditon like <TableCell align="center" >{condition && servicesCode[key]}</TableCell> or like <TableCell align="center" >{condition ? someVariable : "No data here"}</TableCell>