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
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:
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.
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
Hope this helps.