Home > Mobile >  MERN: show buttons based on conditional
MERN: show buttons based on conditional

Time:04-29

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

CodePudding user response:

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: enter link description here

CodePudding user response:

You forgot to include the brackets in your conditional, ever time you want to render something based on some logic or something that's not a component you should include it between brackets

  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}>
      // include brackets here
      {!isCheckout && hasItems ? cartContentButtons : orderDetailsButtons}
    </div>
  );

take a look at react docs to know more about it.

  • Related