I want to add row on every click, but my code is replacing the same row.
Also tried to keep if outside addTable function but this did not work for me.
I tried many solutions but failed. Could anyone please help me here?
I have added my code below, Please check and let me know.
import { useState } from "react";
import "./App.css";
const App = (props) => {
const [count, setCount] = useState(0);
var [items, setItems] = useState([]);
function addTable() {
setCount(count + 1);
if (count <= 10) {
setItems(
<tr>
<td>5 x {count}</td>
<td>{5 * count}</td>
</tr>
);
}
}
console.log(count);
return (
<>
<div className="button">
<button onClick={addTable}>
Click to generate Multiplication tables of 5{" "}
</button>
</div>
<table>
<thead>
<tr>
<th>Multiplication</th>
<th>Results</th>
</tr>
</thead>
<tbody>{items}</tbody>
</table>
</>
);
};
export default App;
>Solution :
Well you’re overwriting items in your onChange, you need to append to it:
setItems([
...items,
<tr>
<td>5 x {count}</td>
<td>{5 * count}</td>
</tr>
]);
But I would probably do instead is:
import { useState } from "react";
import "./App.css";
const App = (props) => {
const [count, setCount] = useState(0);
var [counts, setCounts] = useState([]);
function addTable() {
setCount(count + 1);
if (count <= 10) setCounts([...counts, count]);
}
console.log(count);
return (
<>
<div className="button">
<button onClick={addTable}>
Click to generate Multiplication tables of 5{" "}
</button>
</div>
<table>
<thead>
<tr>
<th>Multiplication</th>
<th>Results</th>
</tr>
</thead>
<tbody>{counts.map((c) => (
<tr>
<td>5 x {c}</td>
<td>{5 * c}</td>
</tr>
)}</tbody>
</table>
</>
);
};
export default App;