'Add loader to particular component which is pressed rather than all other button component in react
I have 2 buttons component, I want the loader to a particular button that is clicked.
Here is my code
import { useState } from 'react';
export default function ProductDetail() {
const [adding, setAdding] = useState(false);
const buttonClicked =() => {
setAdding(true)
.
.
}
return (
.
.
<div>
<button>{ adding ? "Please wait..." : "Add to Cart"}</button>
<button>{ adding ? "Please wait..." : "Buy Now"}</button>
</div>
.
.
);
}
But in this case, both buttons get Please wait... when I click on one of them. I want a loader to that button that is clicked How can I get that
Note: I don't want to create multiple states
Solution 1:[1]
Does this help:
import React, { useState } from "react";
const LoadingStateTest = () => {
const [loadingState, setLoadingState] = useState({
"add-to-cart": false,
"buy-now": false,
});
const handleButtonClick = (e) => {
const targetId = e.target.id;
const isBuying = targetId === "buy-now";
setLoadingState({
"add-to-cart": !isBuying,
"buy-now": isBuying,
});
};
return (
<div>
<button id="add-to-cart" name="Add to Cart" onClick={handleButtonClick}>
{loadingState["add-to-cart"] ? "Please wait..." : "Add to Cart"}
</button>
<button id="buy-now" name="Buy Now" onClick={handleButtonClick}>
{loadingState["buy-now"] ? "Please wait..." : "Buy Now"}
</button>
</div>
);
};
export default LoadingStateTest;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mircea Matei |
