Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}`] : ''}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading