Ramzan Chasygov Ramzan Chasygov - 1 month ago 6
Javascript Question

How do I render JSX based on a condition?

How can I add something like:

if(true) <Reminder /> else <div>hehe</div>


In ordinary way? I know, I can create two
return
statements with
<Reminder />
and without
<Reminder />
, but I don't want to repeat code.

Here is what I have so far:

renderReminders() {
const { reminders } = this.props;
return (
<ListGroup>
{
reminders.map(reminder => {
return (
<ListGroupItem key={reminder.id}>
<div>{reminder.text}</div>
<Reminder dueDate={reminder.dueDate} />
</ListGroupItem>
)
})
}
</ListGroup>
) // return
} // renderReminders



Answer Source

You could use a ternary operator:

{condition ?
  <div>I will render when condition is true!</div>
    :
  <div>I will render when condition is false!</div>
}

This will use an inline JSX expression to conditionally render JSX based on condition. For example:

return (
  <ListGroupItem key={reminder.id}>
    <div>{reminder.text}</div>
    {true ? 
      <Reminder dueDate={reminder.dueDate} />
        :
      <div>Hehe!</div>
    }
  </ListGroupItem>
)