skip to Main Content

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


  1. You need to set keys for components.

    Ref: https://react.dev/learn/rendering-lists

    ...
    let tags = unitLeaders.map(leader => {
        return <Tag closable={true}
                    key={leader}
                    closeIcon={<CloseCircleOutlined/>}
                    onClose={() => clearLeader(leader)}>{leader}</Tag>;
    ...
    
    Login or Signup to reply.
  2. 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.

    return (
      <>
        {unitLeaders.map((leader,index) => (
          <Tag
            key={index}
            closable={true}
            closeIcon={<CloseCircleOutlined />}
            onClose={() => clearLeader(leader)}
          >
            {leader}
          </Tag>
        ))}
      </>
    );
    

    I think it’ll works now.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search