Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

onClick(), I want to add table row

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading