Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

199
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda