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

152
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
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