i am trying to make react notes app with using api , everything works fine but when i add new note , i am facing this warning : Each child in a list should have a unique "key" prop. Check the render method of `Notes`
you can check the notes component here,
{notes.length === 0 ? (
<p>No notes to display</p>
) : (
notes.map(({ id, title, body, created }) => (
<li className="note" key={id}>
<div className="details">
<p>{title}</p>
<span>{body}</span>
</div>
<div className="bottom-content">
<span>{formatDate(created)}</span>
<div
className={`settings ${
showMenu && selectedNoteId === id ? "show" : ""
}`}
>
<AiOutlineEllipsis
className="icon"
onClick={() => toggleMenu(id)}
/>
<ul className={"menu"}>
<li
onClick={() => handleEdit({ id, title, body, created })}
>
<BiPencil />
Edit
</li>
<li onClick={() => toggleDeletePopup(id)}>
<BiTrash />
Delete
</li>
</ul>
{selectedDeleteNoteId === id && (
<DeletePopup
onCancel={handleDeleteCanceled}
deleteConfirmed={() => handleDeleteConfirmed(id)}
/>
)}
{selectedEditNote && selectedEditNote.id === id && (
<EditNotePopup
note={selectedEditNote}
onSubmit={handleNoteUpdate}
onCancel={() => setSelectedEditNote(null)}
/>
)}
</div>
</div>
</li>
))
)}
and here the addnew note component
return (
<div className="newnote-popup">
<div className="card">
<header>
<h3>Add a new note</h3>
<FaTimes className={"x"} onClick={handleCancel} />
</header>
<form onSubmit={handleSubmit}>
<div className="note-title">
<label>Title</label>
<input
type="text"
name="title"
value={note.title}
onChange={handleChange}
maxLength={50}
autoComplete="none"
/>
<small className="character-count">{titleCount}/50 </small>
</div>
<div className="note-body">
<label>Description</label>
<textarea
name="body"
value={note.body}
onChange={handleChange}
placeholder="Your Note"
maxLength={400}
/>
<small className="character-count">{characterCount}/400 </small>
</div>
<div className="buttons">
<button type="submit">Add Note</button>
</div>
</form>
</div>
</div>
);
I searched for this problem and all the solutions were to add unique key, but i am already add the key with id in my code, so what is the problem guys and thanks.
3
Answers
Try this .Rest of the code will remain same
Maybe you’re not getting the unique
id
. Just do thisIn your code snippet, you are indeed assigning a unique key to each "
<li>
" element using the id property from the notes array. This should be correct, and there doesn’t seem to be an issue with the key prop itself.I think, The issue might be elsewhere in your code, possibly in how you’re adding a new note. If you’re adding a new note without assigning a unique id to it before rendering, that could cause the error. Make sure that when you add a new note, you provide a unique id to it before rendering it in the list. Add this code: