Home > Blockchain >  I want to remove the counter when the value reaches to 0 and show the add button again
I want to remove the counter when the value reaches to 0 and show the add button again

Time:08-04

I have created an add button, when clicked it hides and shows a counter to add to cart. But when the counter is made to go zero. I want to show the add button again and hide the counter. How is it possible to do so?

const Card = (product) => {
    const [isActive, setIsActive] = useState(true);

const [quantity, setQuantity] = useState(1);

const handleDecrement = () => {
    if (quantity > 0) {
        setQuantity((prevCount) => prevCount - 1);
    }
};

const handleIncrement = () => {
    if (quantity < 10) {
        setQuantity((prevCount) => prevCount   1);
    }
};



return (
        <>
            <div className="card">
                <div className="product-details">
                    <div className="img-container">
                        <img src={product.img} alt={product.title} />
                    </div>
                    <div className="data-container">
                        <div className="title">{product.title}</div>
                        <div className="subheading">{product.subheading}</div>
                        <div className="price">{product.price}</div>
                    </div>
                </div>
                <div className="button">
                    {isActive && (
                        <button onClick={() => setIsActive(!isActive)}>ADD</button>
                    )}
                    {isActive === false ? (
                        <div className="inc">
                            <span onClick={handleDecrement}>-</span>
                            <span> {quantity} </span>
                            <span onClick={handleIncrement}> </span>
                        </div>
                    ) : null}
                </div>
            </div>
        </>
    );
};

CodePudding user response:

You should render the add button if isActive is set to true, and you'll want to add logic to set isActive to true if quantity is 0

const handleDecrement = () => {
    if (quantity > 0) {
        setQuantity((prevCount) => prevCount - 1);
    }
    else if (quantity === 0) {
        setIsActive(true);
    }
};

This should handle rendering the button correctly

<div className="button">
    { isActive ? (
        <button onClick={() => setIsActive(!isActive)}>ADD</button>
      ) :
      (
        <div className="inc">
            <span onClick={handleDecrement}>-</span>
            <span> {quantity} </span>
            <span onClick={handleIncrement}> </span>
        </div>
      )}
</div>
  • Related