Reputation: 11
I have created a products table. The table has an input field for quantity where the user can add a quantity for a specific product and then add it to the cart.
However, when I type in the input field the values keep disappearing. I was able to get the added product with quantities but still, if input fields stay empty it won't make sense.
const [itemQuantity,setItemQuantity] = useState([]);
How can I provide the input field value attribute from the item quantity Array State?
This code shows how I am getting quantities including the Product Object.
const handleQuantites = (newValue) => {
let found = false;
let newItems = [...itemQuantity];
if (itemQuantity.length > 0) {
for (let index = 0; index < newItems.length; index++) {
if (newItems[index].code === newValue.code) {
newItems[index].Quantity = newValue.Quantity;
found = true;
break;
}
}
if (found) {
return setItemQuantity(newItems);
}
setItemQuantity([...itemQuantity, newValue]);
} else {
setItemQuantity([...itemQuantity, newValue]);
}
};
const BundleColums = useMemo(
() => [
{
Header: "Bundle Name",
accessor: "name",
},
{
Header: "Bundle Category",
accessor: "categoryName",
},
{
Header: "Bundle Status",
accessor: "status",
},
{
Header: "Quantity",
accessor:"Quantity",
Cell: ({ cell }) => (
<Fragment>
<input
type={"text"}
placeholder="Add Quantity b"
className="form-control"
onChange={(e) => {
handleQuantites({
...cell.row.original,
Quantity: e.target.value,
});
}}
min={0}
/>
</Fragment>
),
},
{
Header: "Actions",
Cell: ({ cell }) => (
<Fragment>
<button
className="btn btn-primary "
onClick={() => {
handleAddToCart(cell.row.original);
}}
>
Add to Cart
</button>
</Fragment>
),
},
],
[itemQuantity]
);
Image of what my table looks like:
As I keep adding Quantity it keeps disappearing!
Upvotes: 1
Views: 2980
Reputation: 593
From my point of view, if you try it according to the example below, it might work as you want:
{
Header: "Quantity",
accessor:"Quantity",
Cell: ({ cell }) => (
<Fragment>
<input
type={"text"}
placeholder="Add Quantity b"
className="form-control"
onChange={(e) => {
handleQuantites({
...cell.row.original,
Quantity: e.target.value,
});
}}
value={cell.row.original.Quantity}
min={0}
/>
</Fragment>
),
},
`
Upvotes: 0
Reputation: 488
You can add the state value to the input <input ... value={<PUT STATE HERE>} />
It will auto-update on state changes. Check out https://reactjs.org/docs/forms.html#:~:text=%3Cinput%20type%3D%22text%22%20value%3D%7Bthis.state.value%7D%20onChange%3D%7Bthis.handleChange%7D%20/%3E
Upvotes: -1