I am trying to build a table-like structure in which I want to add rows dynamically. Here is my code:
import { React, useState } from 'react';
function Table() {
const [add, setAdd] = useState(false);
return (
<div>
<div className="headings">
<p>Item Description</p>
<p>Quantity</p>
<p>Rate</p>
<p>Amount</p>
</div>
<div className="rows">
<input placeholder="Item Description" type="text" />
<input placeholder="Quantity" type="number" />
<input placeholder="Price per piece" type="number" />
<input placeholder="Amount" type="number" />
</div>
{
add ?
<div className="rows" >
<input placeholder="Item Description" type="text" />
<input placeholder="Quantity" type="number" />
<input placeholder="Price per piece" type="number" />
<input placeholder="Amount" type="number" />
</div>
:
<div></div>
}
<button className="add" onClick={()=>setAdd(true)}>Add another line item</button>
</div>
)
}
export default Table;
I have tried adding rows using the button but I am able to add only a single row. The state changes to true so can I reset the state or should I use any other method for adding rows?
You need to set a counter in order to track how many rows you have, and preferably pass it on to another component.
This is not a complete example, but the essence is there:
import { React, useState } from "react";
function Rows({ numberOfRows }) {
return [...Array(numberOfRows)].map((element, index) => (
<div key={index}>{`Row Number ${index}`}</div>
));
}
function Table() {
const [numberOfRows, setNumberOfRows] = useState(0);
const addRow = () => {
setNumberOfRows((prev) => prev + 1);
};
const deleteRow = () => {
if (numberOfRows > 0) {
setNumberOfRows((prev) => prev - 1);
}
};
return (
<div>
<div className="headings">
<p>Item Description</p>
<p>Quantity</p>
<p>Rate</p>
<p>Amount</p>
</div>
<Rows numberOfRows={numberOfRows} />
<button className="add" onClick={addRow}>
Add row
</button>
<button className="delete" onClick={deleteRow}>
Delete row
</button>
</div>
);
}
export default Table;