Home > Net >  Antd item.list removes always removes first last element
Antd item.list removes always removes first last element

Time:06-04

Hi there I made simple antd list where user can add, remove edit list. But the problem is that when i add, edit list verything works as it should. But when i remove item from a list, antd always remove last item from a list. Although i can remove any item.

  const [employeeList, setEmployeeList] = useState([])
    <List
      dataSource={employeeList}
      renderItem={(item, index) => (
       <List.Item id='listItem' >
         <Input 
          id='listItem-input'
          defaultValue={item.name} 
          onChange={(i) => {
            employeeList[index].name = i.target.value
            setEmployeeList(answerList)   
          }}
        />
        <span className='removeItem' 
          onClick={() => {
            let newList = setEmployeeList
            newList[index] = undefined
            setEmployeeList(newList.filter(e => e))
           }}
         >
           <CloseOutlined/>
         </span>
       </List.Item>
     )}
  />

I checked in console items in state gets removed, although it still stays in item.list

CodePudding user response:

First of all I would recomend deleting items with splice()

so rather then this 3 lines in onClick (in remove) just

employeeList.splice(index,1)

Edit:

With your approach you probably want:
 let newList = employeeList
 newList[index] = undefined

CodePudding user response:

Turns out i had to use a keys. List.Item wasn't registering changes without keys and was just deleting last item, on any change.

<List.Item id='listItem' key={item.answer} >
  • Related