jsx: ReactJS if condition

Viewed 122

How to use if condition in jsx: ReactJS? I just want that if the

if user == "author" or "supervisor":
<IconButton 
   aria-label="delete" 
   onClick={() => props.pressHandler(props.id)}
 >
  <DeleteIcon style={{ color: 'red' }} />
</IconButton>
else
     no delete button
3 Answers

To elaborate on what Stark wrote:

You can use the js operator as such:

{(
 (user === "author" || user === "supervisor") && 
<IconButton 
   aria-label="delete" 
   onClick={() => props.pressHandler(props.id)}
 >
  <DeleteIcon style={{ color: 'red' }} />
</IconButton>
) || undefined
}

Same above with ternary operator and React Fragment:

{
(user === "author" || user === "supervisor") ?
<IconButton 
   aria-label="delete" 
   onClick={() => props.pressHandler(props.id)}
 >
  <DeleteIcon style={{ color: 'red' }} />
</IconButton> : <></>
}

In false case, Undefined or React.Fragment wont be rendered.

{
  ["author", "supervisor"].includes(user) ? (
    <IconButton
      aria-label="delete"
      onClick={() => props.pressHandler(props.id)}
    >
      <DeleteIcon style={{ color: "red" }} />
    </IconButton>
  ) : null;
}

When you use "&&" operator sometimes you can see "false" text on your app. null will be great option to display nothing or use can put something differrent than delete button for regular user as null.

Related