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

153
Visualizações
Removing the corresponding div on clicking delete using react

I'm to add/remove the row dynamically on clicking the button. When I add its adding properly like when there are 1,2,3,4 rows and when I click add on 2 row its adding new row as 3. But when I delete the particular row, its always deleting the last row. Here I've passed the index from map, but even then its removing last element only.

https://codesandbox.io/s/add-remove-items-p42xr?file=/src/App.js:0-1099

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Here is a working snippet. It uses a ref to keep track of id's to avoid duplicates, and uses element.order as key instead of index. The remove method has been changed to use a callback passed to setState and a filter() call to remove the elements based on passed order property.

const { useState, useRef } = React;

const App = () => {
  const [formValues, setFormValues] = useState([
    { order: 1, type: "", name: "", query: "" }
  ]);
  const id_index = useRef(1);

  let addFormFields = () => {
    setFormValues([
      ...formValues, 
      { order: (id_index.current += 1), type: "", name: "", query: "" }
    ]);
  };

  let removeFormFields = (order) => {
    setFormValues(prev =>  prev.filter(element => element.order !== order));
  };

  return (
    <div>
      {formValues.length ?
        formValues.map((element) => (
          <div className="form-inline" key={element.order}>
            <label>{element.order}</label>

            <input type="text" name="hello" />

            <button
              className="button add"
              type="button"
              onClick={() => addFormFields()}
              disabled={formValues.length >= 4}
            >
              Add
            </button>
            <button
              type="button"
              className="button remove"
              onClick={() => removeFormFields(element.order)}
            >
              Remove
            </button>
          </div>
        ))
        : null}
    </div>
  );
};

ReactDOM.render(
  <App  />,
  document.getElementById("app")
);
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>

<div id="app"></div>

about 4 years ago · Juan Pablo Isaza Relatório

0

Two things you have to update,

  1. update the addFormFields method
  2. update the removeFormFields method

https://codesandbox.io/s/add-remove-items-forked-so-sqoqk?file=/src/App.js:378-394

Here is the codesanbox link for your reference.

about 4 years ago · Juan Pablo Isaza Relatório
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