Can you apply three different classes to a React component conditionally?

Every answer I’ve seen on this uses the ternary operator which only allows for two conditions if/else. But I have this below component where I need three separate classes applied conditionally. I want it to apply no class if selected is false, to apply ‘toggle-user’ if it is selected and roleTable is false, and to apply ‘toggle-role’ if it is selected and roleTable is true.

return (
<>
  <tr
    className={(selected && !roleTable) ? styles[`toggle-${selection}`] : ""}
    onClick={toggle}
  >
    <td className={cols ? styles[`person-row`] : styles["user-row"]}>
      <div className={cols ? styles[`person-col`] : ""}>
        {cols ? props.user.name : props.user}
      </div>
      {cols ? (
        <>
          <div className={styles["person-col"]}>{props.user.email}</div>
          <div className={styles["person-col"]}>{props.user.role}</div>
        </>
      ) : null}
    </td>
  </tr>
</>
);
};

export default User;

>Solution :

The conditional operator can be nested. Consider creating the class name as a standalone statement beforehand for readability.

const trClassName = !selected
  ? ''
  : roleTable
    ? 'toggle-role'
    : 'toggle-user';
return (
<>
  <tr
    className={trClassName}
    onClick={toggle}
  >

If 'selection' is either 'role' or 'user', then you don’t need to nest the conditional; unconditionally use toggle-${selection} if selected is true.

className={selected ? `toggle-${selection}` : ''}

or if the class name you want to use is in the styles object

className={selected ? styles[`toggle-${selection}`] : ''}

Leave a Reply