Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

193
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda