javascriptreactjsreact-hooksmaterial-uimui-datatable

Conditional rendering and executing on React


I use Material Datatable in my React app and want to render the following part conditionally if data is not null or undefined. It is also ok for me not to execute Object.entries(data).map(x => ( line.

<TableBody >
{
    Object.entries(data).map(x => (
      <TableRow key={x[0]}>
        <TableCell className="tableCell">{x[0]}</TableCell>
        <TableCell className="tableCell">{x[1]}</TableCell>
      </TableRow>
    ))
}
</TableBody>

So, how can I do this properly?


Solution

  • There are two actions you can apply to render components under a condition.

    1. <expression> && <true> In JS one quirky behaviour is that if <expression> evaluates to true, the second expression <true> is returned. You can make use of this if you just don't want to render anything if <expression> evaluates to false.
    2. <expression> ? <true> : <false> This is useful if you want to render something in any case. This is called a ternary operator, nd you can think of it as an inline if-else statement that returns either the <true>- or the <false> expression, depending on what <expression> evaluates to.

    Now, to check whether your data is valid or not, JS has another useful feature: Truthy/falsy values. ""(empty string), 0, null, undefined are coersed into the false value if used in a logical expression. So you can just check if data is valid by putting your data object into <expression>. And since this becomes a logical value, you can use the ! in the beginning of the <expression> to toggle the values.

    Some examples:

    {!data && <NoDataComponent /> /* Only renders if data is falsy */}
    {data && <DataComponent /> /* Only renders if data is there */}
    
    {data ? <DataComponent /> : <NoDataComponent /> /* Renders always one of the components but never both at the same time! */}