How to delete the exact item on the list when I click the delete button?

Viewed 83

What im trying to do is for the user to edit his language (add new or remove the current one). The language is on the array

So in my console, the language comes language in edit component: ["English", "German"]

Languages.js

export default function Languages({ email, setEmail }) {

  const deleteLanguage = (index) => {
    const list = [...language];
    list.splice(index, 1);
    setLanguage(list);
  };

  return (
    <div>
      {language.map((o, i) => {
        return (
          <tr key={"item-" + i}>
            <td>
              <div>
                <input
                  type="text"
                  value={language}
              </div>
            </td>
            <td >
              <button
                type="button"
                onClick={deleteLanguage}
              >
                Delete
              </button>
            </td>
          </tr>
        );
      })}
  );
}

enter image description here

So when I delete the first item on the list, which is German, it will be deleted, but when I delete the second item on the list, which is English, it will delete the German, and the English will remain. And If a add a third language, and delete the third language, still the first item on the list will be deleted.

How can I solve this

1 Answers

You need to pass the item index in the handleRemove funciton.

          <button
            type="button"
            onClick={() => handleRemoveClick(i)}
          >
            Delete
          </button>
Related