Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

191
Views
react remove specific item from state array

I try to make a table and to create row on each click on button, to do that, I made 2 useStates -

const [rowsInTable, setRowsInTable] = useState([0]);
const [addedRows, setAddedRows] = useState([]);

this is the function that runs on button click -

const addRowFunc = (e, newRow) => {
  e.preventDefault();
  const add = setRowsInTable([...rowsInTable, newRow]);
            
  rowsInTable.map((row, index) => {
    return setAddedRows([
       ...addedRows,
       <tr key={index}>
          <td>
             <input type="file" />
          </td>
          <td>
             <input type="text" />
           </td>
          <td>
             <input type="text" />
          </td>
          <td>
             <input type="text" />
          </td>
          <td>
             <input type="text" />
          </td>
          <td>
             <TextareaAutosize minRows={2} />
          </td>
          <td>
             <input type="date" name="" id="" />
          </td>
          <td>
             <input type="date" name="" id="" />
          </td>
          <button key={index} onClick={(e) => deleteRow(e, index)} className="deleteButton">X</button>
       </tr>,
     ]);
  });
};

and as you can see it renders a button for each that run another function on click that removes the table row..

this it the function:

const deleteRow = (e, index) => {
  e.preventDefault();
            
  const rowsNum = [rowsInTable]
  const rowsElements = [addedRows]
            
  rowsNum.splice(index, 1)
  rowsElements.splice(index, 1)

  setRowsInTable(...rowsNum)
  setAddedRows(...rowsElements)
}

so 2 things.. the first one is that when i try to delete a row the row with the index I click on get deleted but it also delete the all next in the array.. if i click index-5 and i have 10, 5-10 gets deleted..

second thing is, I want the state to start clean or overwrite the 0 in the array after first interaction.. can't come up with a solution for that, so i'll appreciate one..

thanks! :)

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!