Home > front end >  Removing the corresponding div on clicking delete using react
Removing the corresponding div on clicking delete using react

Time:10-02

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

CodePudding user response:

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>

CodePudding user response:

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.

  • Related