简体   繁体   中英

delete specific index of array based onClick in React.js

I have a row consisting of a textbox and a button.

These rows can be added after clicking add new row button with the following code:

  1. useState: const [newSertifikasi, setNewSertifikasi] = useState(0)

  2. Load a row: ...Array(newSertifikasi).map((i) => ("components here"))

  3. Adds a new row: onClick={() => setNewSertifikasi(newSertifikasi + 1)}

I want to create a method of deleting rows by clicking on a button that is in a particular row.

I have used the "splice" and "filter" methods, but found a dead end

Here's the full code: https://codepen.io/febry-aryo-riandhito/pen/BaRpNKQ

you can remove the element by it index using splice like this, the function could be shorter but for sake of understanding this is a good solution.

function deleteByIndex(index){
     setNewSertifikasi(current => {
         const newArr = current;
         newArr.splice(index, 0);
         return newArr;
      })
}

a shorter version could be this

function deleteByIndex(index){
     setNewSertifikasi(current => [...current.splice(index, 1)])
}
let test = ['test01', 'test02', 'test03']

test.splice(1,1); // this delete specific index

console.log(test) // ['test01', 'test03']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM