skip to Main Content

How to change from "Add To Cart" to "Added To Cart" in react.js on clicking the "Add To Cart" button?
Here is my "Add To Cart" button.

<button
className="btn"
onClick={() =>
    addProductToCart(products)
    }
>
Add to cart
</button>

Here is the addProductToCart handler

const addProductToCart = (product) => {
            const newProduct = {
                ...product,
                count: 1,
            };
            setProducts([
                ...productsInCart,
                newProduct,
            ]);
        };
    

Can I achieve this using useState?

2

Answers


  1. Yes, you can achieve the desired behavior using the useState hook in React. Here’s an example of how you can modify your code to change the text from "Add to cart" to "Added to cart" when the button is clicked:

        import React, { useState } from 'react';
        
        const Product = () => {
          const [cartStatus, setCartStatus] = useState('Add to cart');
        
          const addProductToCart = (product) => {
            const newProduct = {
              ...product,
              count: 1,
            };
            setProducts([...productsInCart, newProduct]);
            setCartStatus('Added to cart');
          };
        
          return (
            <button className="btn" onClick={() => addProductToCart(products)}>
              {cartStatus}
            </button>
          );
        };
    
    export default Product;
    

    In this code, a new state variable cartStatus is introduced using the useState hook. It initially holds the value "Add to cart". When the button is clicked, the addProductToCart function is called, which updates the state variable to "Added to cart" using setCartStatus. This causes the button’s text to be updated accordingly.

    Login or Signup to reply.
  2. The previous answer is correct if you have one Product in that page. From your comments, I can see that each product has Add to cart button. In this case your product object should have a property ‘isAddedToCart’. You need to use map function to display button for each products as well

    Here is the sample code

      const addProductToCart = (product) => {
                const newProduct = {
                    ...product,
                    count: 1,
                    isAddedToCart: true
                };
                
                setProducts(products.map(p => (p.id === newProduct.id 
       ? newProduct : p)))};
            return ({
        products.map(p => (
    <button
        className="btn"
        key={p.id}
        onClick={() =>
            addProductToCart(p)
            }
        >
        {p.isAddedToCart ? 'Added to Cart' : 'Add to Cart'}
        </button>
    ))
    

    Hope this helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search