Answer the question
In order to leave comments, you need to log in
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
First, it's a key
bad 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 questionAsk a Question
731 491 924 answers to any question