Question:
Fix react useState and array.map not work issue

Problem:

I saw a lot of similar questions and answers, but still do not understand what I'm doing wrong.

I want to display an 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?


Solution:

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>;

...



Suggested blogs:

>What makes index.html have such kind of name in Django?

>Fix Module Not Found during deployment- Django

>Creating a Django with existing directories, files etc.?

>Fix Module Not Found Error in Django

>How to create a to-do list for users, with only incomplete tasks in Django?

>How to populate Django Quill Field from ORM

>How to test the post-Django function?

>How to filter events by month in Django?

>Implement nested serializers in the Django rest framework



Ritu Singh

Ritu Singh

Submit
0 Answers