I have created a state in which it will contain the row value of a table.
const [poItem, setPoItem] = useState<any>([]);
const [index, setIndex] = useState<number>(0);
const [table] = useState<any>([]);
const addRow = (event: any) => {
event.preventDefault();
setIndex(index + 1);
const input = (
<TableRow
key={index}
className={`add-po-item-box-${index}`}
sx={{
"& td": { padding: 0 },
}}
>
<TableCell align="center">{index + 1}</TableCell>
<TableCell>
<Autocomplete
className="input-item form-input"
options={dataStock}
onChange={(event: any, value: any) => {
if (!value) {
return;
}
handleChangeRow(index, "stockId", value.id);
}}
renderInput={(params) => (
<TextField {...params} label="Choose Item" />
)}
/>
</TableCell>
<TableCell>
<TextField
className="input-quantity form-input"
defaultValue={0}
name={"quantity"}
type="number"
inputProps={{
maxLength: 3
}}
onChange={(event: any) =>
handleChangeRow(index, "quantity", event.target.value)
}
required
/>
</TableCell>
<TableCell>
<TextField
className="input-price form-input"
name={"price"}
type="number"
disabled
/>
</TableCell>
<TableCell>
<TextField
className="input-total form-input"
name={"price"}
type="number"
disabled
/>
</TableCell>
</TableRow>
);
table.push(input);
};
the addRow function is to add the row into the state of table
another function which will handle the state value
const handleChangeRow = (idx: number, fieldName: string, fieldValue: any) => {
setPoItem((prevData: any) => {
const newData = [...prevData];
let price = prevData[index]?.price;
if (fieldName === "stockId") {
const data = dataStock.filter((x: any) => x.id === fieldValue);
price = data[0].item.vendorPrices[0].price;
}
newData[idx] = {
...newData[idx],
vendorId: inputs.vendorId,
price: price,
[fieldName]: fieldValue,
};
return newData;
});
};
the way I show the input row is
<TableBody>{table}</TableBody>
Here’s the sample picture
And here’s the result of the state when being inputted
I’m expecting the PRICE input to be taken from the state of price and the total will be the quality x price, as I tried it, those 2 values are always 0.