Search code examples
reactjsconditional-operator

MERN: show buttons based on conditional


I'm using React.JS and I'm trying to show a group of buttons based on the state of a variable, this is the code snippet:

  const cartContentButtons = (
    <button className={classes["button--alt"]} onClick={props.onClose}>Close</button> &&
    <button className={classes["button--alt"]} onClick={orderHandler}>Order's Details</button>    
  );

  const orderDetailsButtons = (
    <button className={classes["button--alt"]} onClick={props.onClose}>Close</button> &&
    <button className={classes["button--alt"]} onClick={orderHandler}>Cart's Content</button> &&    
    <button className={classes["button--alt"]} onClick={orderHandler}>Order's Checkout</button>        
  );

  const modalActions = (
    <div className={classes.actions}>
      !isCheckout && hasItems ? cartContentButtons : orderDetailsButtons;
    </div>
  );

However, during code execution this is the result:

showing buttons

What am I missing to display the buttons properly?

Thanks a lot


Solution

  • You must wrap your conditional statement in curly braces and remove the semicolon at the end.

    <div className={classes.actions}>
      {!isCheckout &&
        hasItems ? cartContentButtons : orderDetailsButtons
      }
    </div>
    

    Look at the documentation