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?
3
Answers
Just verify if data exists
By adding && condition will handle null and undefined check for you
If you want to write condition operator
There are two actions you can apply to render components under a condition.
<expression> && <true>
In JS one quirky behaviour is that if<expression>
evaluates totrue
, the second expression<true>
is returned. You can make use of this if you just don’t want to render anything if<expression>
evaluates tofalse
.<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 thefalse
value if used in a logical expression. So you can just check if data is valid by putting yourdata
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: