I saw a lot of similar questions and answers but still do not understand what I’m doing wrong.
I want to display array of elements.
const [unitLeaders, setUnitLeaders] = useState([])
let tags = unitLeaders.map(leader => {
return <Tag closable={true}
closeIcon={<CloseCircleOutlined/>}
onClose={() => clearLeader(leader)}>{leader}</Tag>;
})
<Space wrap>
{tags}
</Space>
add new element
const onClick = ({key}) => {
setUnitLeaders([...unitLeaders, key])
};
remove selected element
const clearLeader = (leader) => {
setUnitLeaders(unitLeaders.filter(item => item !== leader))
};
Adding is working fine, but when im trying to delete element I got invalid array displayed. What I did wrong?
2
Answers
You need to set keys for components.
Ref: https://react.dev/learn/rendering-lists
In your code, if state is updated tags is not updated.
Because updating state means ‘component update’, not ‘component mount’.
So tags is inited at first => ‘component mount’ and not update forever.
To solve this problem, you need to use unitLeaders in return like below.
I think it’ll works now.