How To Add Rows Dynamically On Input Value In React JS

In this article, we learn how to add rows dynamically on input change.

First, open our React app then take the input field, and on the change event set the value in one state.

<input placeholder="number" name="number" onChange={changeNumber} />

const changeNumber = (e) => {
  setnumber(e.target.value);
};

Now take a blank array, inside that push the number of rows which is the value of the input.

const numberArray = [];

for (let i = 1; i <= number; i++) {
  numberArray.push(
    <td>{i}</td>
  );
}

Now create a map of that array and show that after table inside a table tag.

So, my App.js looks like this,

import React, { useState } from "react";

export default function App() {
  const numberArray = [];
  const [number, setnumber] = useState(0);
  const changeNumber = (e) => {
    setnumber(e.target.value);
  };

  for (let i = 1; i <= number; i++) {
    numberArray.push(
      <td>{i}</td>
    );
  }

  return (
    <div>
      <div>
        <label>Enter Number of row: </label>
        <input
          placeholder="number"
          name="number"
          onChange={changeNumber}
        />
      </div>
      <table border={1}>
        <tr>
          {numberArray}
        </tr>
      </table>
    </div>
  );
}

Output:-

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories