Nika Roffy
Nika Roffy

Reputation: 941

Get id of item on which button was clicked reactjs javascript

I have an object array like this( in Reactjs functional component) which has this guys :

--------comments (6) [{…}, {…}, {…}, {…}, {…}, {…}]

0(pin):{comment:'1',commentid:264}
1(pin):{comment:'2',commentid:265}
2(pin):{comment:'5',commentid:266}
3(pin):{comment:'1',commentid:267}
4(pin):{comment:'2',commentid:268}
5(pin):{comment:'test',commentid:269}

I have them displayed on page. I want to get id of the object i click. Here is my function.

const deleteComment = (id : Number) => {
    console.log('--------id', id);
}

I tried to do map,filter or foreach but nothing worked,any suggestions please?

<ul>
                        {
                            comments.map((items: any) => {
                                return (
                                    <p
                                        key={uuidv4()}
                                    >Comment : {items.comment}
                                    <button onClick={() => {deleteComment(items.commentid)}}>Delete</button>
                                    </p>
                                );
                            })}
                    </ul>

Update (I restarted the app and everything works fine now)

Upvotes: 0

Views: 63

Answers (1)

amdev
amdev

Reputation: 7432

on your deleteComment function , I assume that you are passing the id of clicked comment to the function, you need to do something like this:


const deleteComment = (id : Number): void => {
   const foundComment = comments.find(item => item.commentid === id)
}

this would give you the clicked item, for deleting it , you need to find the index first and then slice the array of comments and set it in your state or return it of what ever you need to do, in below code snippet i try to remove it from comments array:


const deleteComment = (id : Number): void => {

    /** this would give you the index of found item, other vise it would return -1 */
    const foundIndex = comments.findIndex(item => item.commentid === id)

    if(foundIndex !== -1) {
       
       const newCommentsArr = [
           ...comments.slice(0, foundIndex),
           ...comments.slice(foundIndex + 1, comments.length - 1)
       ]

       /** you can setState the `newCommentsArr` or do what ever you want with it */
      
    }

}

Upvotes: 1

Related Questions