React dont render null values in cell using string literal

Viewed 453

I dont want to render null for address2 and address3 if the user has not input a value. Could anyone tell me a good day of doing it. Thanks

result.map((row) => (
    <TableRow key={row.name}>
       <TableCell align="center">
           {`${row.address1} ${row.address2} ${row.address3}`}
       </TableCell>
    </TableRow>
))}
4 Answers

I think a good way could be to keep addresses in an array that you can filter and join like this:

{
  result.map((row) => (
    <TableRow key={row.name}>
      <TableCell align="center">
        {[row.address1, row.address2, row.address3].filter(i => i).join(' ')}
      </TableCell>
    </TableRow>
  ))
}

In my opinion there is no reason to render a templating string inside a templating language. Why not use the templating language to your advantage, JSX already hides render output if null is returned.

Applying the above something like this would do the trick:

<TableCell align="center">
    {row.address1} {row.address2} {row.address3}
</TableCell>

This will leave 2 spaces between address 1 and 3 if 2 is not present. However HTML collapses adjacent whitespace into a single space, so this shouldn't be an issue.

You could check if the variables are set and render them accordingly:

result.map((row) => (
    <TableRow key={row.name}>
       <TableCell align="center">
           {`${row.address1}${row.address2 ? " " + row.address2 : ""}${row.address3 ? " " + row.address3 : ""}`}
       </TableCell>
    </TableRow>
))}

Have you tried this?

result.map((row) => (
    <TableRow key={row.name}>
       <TableCell align="center">
         {row.address1}
         {" "}
         {row.address2}
         {" "}
         {row.address3}
       </TableCell>
    </TableRow>
))}
Related