I
I
Ilia V. Soldatkin2022-02-09 22:29:02
React
Ilia V. Soldatkin, 2022-02-09 22:29:02

How to use keys in React to remove an element?

How to refer to key here in order to use it in the element removal function?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2022-02-09
@iliyasold

First, it's a keybad idea to use the index number in an array as , especially when you're going to modify that array. The key must be hard-wired to a specific element, indexes in the array do not provide this.
Secondly, the CommentItem component, which at some point calls the function passed to it removeItem(), must pass into it the very identifier by which you will delete the element.
Sample code:

{comments.map((comment) => (
  <CommentItem
    key={comment.id}
    id={comment.id}
    userName={comment.userName}
    commentText={comment.commentText}
    currentDate={comment.currentDate}
    currentTime={comment.currentTime}
    removeItem={removeCommentItem}
  />
)}

CommentItem = (id, removeItem) => {
   return (
    <button onClick={() => removeItem(id)}>Удалить</button>
  )
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question