Home > OS >  How can I hide the variable rendering on JSX React?
How can I hide the variable rendering on JSX React?

Time:01-27

I'm making a e-commerce cart and I displaying the total price value of all items. But when I do a conditional render like this (in case no products is loaded):

{cartItems.length &&
            <div>
                <p>Total price: $ {totalPrice} </p>
                <button onClick={confirmPurchase}>Confirm purchase</button>
            </div>}

instead of displaying anything, React render a "0" because of the variable "totalPrice". How can I hide it?

CodePudding user response:

When you use the && operator and the first value is falsey (in your case, your cartItems.length will evaluate to 0), it will return the falsey value - 0.

Another way to achieve this is by using a ternary operator. You could be explicit here and define when you want to show the items and when not:

{cartItems.length > 0 ? (
  <div>
    <p>Total price: $ {totalPrice} </p>
    <button onClick={confirmPurchase}>Confirm purchase</button>
  </div>
) : null}
  •  Tags:  
  • Related