Bishonen_PL
Bishonen_PL

Reputation: 1571

conditional enclosing elements React

Having a simple react Component:

<Table>
  <TableBody>
    <TableCell>
      x
    </TableCell>
  </TableBody>
</Table>

How can I conditionally enclose the TableBody in yet another component (e.g. Paper)? I thought of something like the below, but this does not seem to do it.

<Table>
  {paper && <Paper>}
  <TableBody>
    <TableCell>
      x
    </TableCell>
  </TableBody>
    {paper && </Paper>}
</Table>

Upvotes: 0

Views: 102

Answers (2)

Nicholas Tower
Nicholas Tower

Reputation: 84912

If you want to avoid repeating the code for the Table body, you can assign it to a variable and use that.

const content = (
  <TableBody>
    <TableCell>
      x
    </TableCell>
  </TableBody>
);

return (
  <Table>
    {paper ? <Paper>{content}</Paper> : content}
  </Table>
)

Upvotes: 5

Dinesh Kumar
Dinesh Kumar

Reputation: 488

You can do it this way. I considered null condition for paper variable, you can do it with any.

<Table>
      {paper !== null ? (
        <Paper>
         <TableBody>
          <TableCell>
           x
          </TableCell>
         </TableBody>
        </Paper>
      ):(<TableBody>
        <TableCell>
          x
        </TableCell>
      </TableBody>)} 
</Table>

Upvotes: 0

Related Questions