Home > front end >  Dynamically Delete Elements
Dynamically Delete Elements

Time:01-02

I'm having trouble deleting elements. Instead of deleting a specific element, it only deletes the last newly created element. I'm not sure where I'm going wrong here. I referenced enter image description here

Deletes Last Created:

enter image description here

CodePudding user response:

I think the main problem is the key of items that you set as react doc says:

When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort:

const todoItems = todos.map((todo, index) =>
  // Only do this if items have no stable IDs
  <li key={index}>
    {todo.text}
  </li>
);

We don’t recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state. Check out Robin Pokorny’s article for an in-depth explanation on the negative impacts of using an index as a key. If you choose not to assign an explicit key to list items then React will default to using indexes as keys.

As in this Article says:

Reordering a list, or adding and removing items from a list can cause issues with the component state, when indexes are used as keys. If the key is an index, reordering an item changes it. Hence, the component state can get mixed up and may use the old key for a different component instance.

What are some exceptions where it is safe to use index as key?

-If your list is static and will not change.

-The list will never be re-ordered.

-The list will not be filtered (adding/removing items from the list).

-There are no ids for the items in the list.

If you set an reliable key in your items with some counter or id generator your problem would solve.

something like this:

export default function App() {
  const [list, setList] = useState([]);
  const id = useRef({ counter: 0 });

  const AddInput = () => {
    console.log(id);
    setList([...list, { placeholder: "Class Name", id: id.current.counter   }]);
  };

  const DeleteInput = (id) => {
    setList(list.filter((item, i) => item.id !== id));
  };

  const InputChangeHandler = (event, index) => {
    const l = [...list];
    l[index].value = event.target.value;
    setList(l);
  };

  return (
    <div>
      <button onClick={AddInput}>Add</button>
      {list.map((item, key) => (
        <div key={item.id}>
          <input
            type={"text"}
            id={key}
            placeholder={item.placeholder}
            onChange={(e) => InputChangeHandler(e, key)}
          />
          <button id={item.id} onClick={() => DeleteInput(item.id)}>
            Delete
          </button>
        </div>
      ))}
    </div>
  );
}

CodePudding user response:

Use filter.

const DeleteInput = (index) => {
  const l = list.filter((_, i) => i !== index);
  setList(l);
};

CodePudding user response:

Pass id to your DeleteInput function and for remove just filter the item list with id

const DeleteInput = (id) => {const filterItemList = list.filter((item) => item.id!== id);setList(filterItemList ); };
  • Related