'How to change button in reactjs on click based on API data
I am trying to build a small e-commerce site and would like to change Add Button button on click to a re-rendered button
{productList !== null ? productList.map((item, index) => (
<div className="container px-0">
<div className="col d-flex flex-row justify-content-between ms-2">
<p className="fs-large-semibold my-0">
{item.title} {item.skuRid}
</p>
{
count !==0 && cartList !== null ? cartList.map((citem,index) => (
<>
{citem.skuRid === item.skuRid?
<>
<div className=" btn btn-box mx-2 px-3 py-0 d-flex flex-row">
{isDecrement && loadedTarget === ('btn' + index) ? <span
className="spinner-border spinner-border-sm me-2 my-auto"
role="status">
</span> : <button className=" btn my-auto p-0 fs-small-reg text-green" name={'btn' + index} value={state['btn' + index] == null ? item.qty : state['btn' + index]}
onClick={(e) => { setValueDecrement(e, item.skuRid) }}>-</button>}
<p className=" mx-2 my-auto fs-small-reg text-green" >{state['btn' + index] == null ? state['btn' + index] : state['btn' + index]}</p>
{isIncrement && loadedTarget === ('btn' + index) ? <span
className="spinner-border spinner-border-sm me-2 my-auto"
role="status">
</span> : <button className="btn ms-0 my-auto p-0 fs-small-reg text-green" name={'btn' + index} value={state['btn' + index] == null ? item.qty : state['btn' + index]}
onClick={(e) => { setValueIncrement(e,item.skuRid) }}>+</button>}
</div>
</> : null}
</>
)): null}
<button onClick={() => {addCart(item.skuRid) }} className="btn btn-box btn-outline-success fs-normal-med text-green py-0 me-2">Add</button>
Above is my code. productList returns an object with a list of products and I'm comparing it with items in cartList and if the item of id (skuRid) exists in the cartList, I need to re-render the add button. Count keeps the count of items in cart. Increment / Decrement increases and decreases the quantity of items. Currently when I click "Add" button, both the buttons are dispalyed in my UI.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
