Home > Net >  React error: "Each child in a list should have a unique "key" prop."
React error: "Each child in a list should have a unique "key" prop."

Time:11-14

Hi I am getting an error that says "each child in a list should have a unique "key" prop. When I check the Components using React Developer Tools I don't see any duplicates - what am I doing wrong?

  return (
    <>
    <Modal
        isOpen={modalIsOpen}
        onRequestClose={closeModal}
    >
      { modalIsOpen ? (
        <Note
        key={'ModalNote'   modalNote.id}
        id={modalNote.id}
        title={modalNote.title}
        text={modalNote.text}
        date={modalNote.date}
        deleteNote={deleteNote}
        closeNote={closeModal}
        />
      ) : ('')
      }
      
    </Modal>
    <div className="notesForm">
      <AddNote addNoteHandler={addNoteHandler}/>
    </div>
    <div className="notes">
      {notes.map((note) => (
        <>
        <Note
          key={note.id}
          id={note.id}
          title={note.title}
          text={note.text}
          date={note.date}
          deleteNote={deleteNote}
          closeNote={closeModal}
          openModal={openModal}
          modalIsOpen={modalIsOpen}
        />
        </>
      ))}
    </div>
    </>
  );

CodePudding user response:

Try this, Instead of Fragment add div, It might works. -> And if You want Fragment then:

<React.Fragment key={note.id}>

  <div key={note.id}>
    <Note
      key={note.id}
      id={note.id}
      title={note.title}
      text={note.text}
      date={note.date}
      deleteNote={deleteNote}
      closeNote={closeModal}
      openModal={openModal}
      modalIsOpen={modalIsOpen}
    />
  </div>

CodePudding user response:

The keys are to be added to the outermost element returned from the map

Here in your e.g its the fragment <>, to add the key to the fragment you should be using <React.Fragment> for shorthand as shorter syntax doesn't support keys

{notes.map((note) => (
        <React.Fragment key={note.id}>
        <Note
          key={note.id}
          id={note.id}
          title={note.title}
          text={note.text}
          date={note.date}
          deleteNote={deleteNote}
          closeNote={closeModal}
          openModal={openModal}
          modalIsOpen={modalIsOpen}
        />
        </React.Fragment>
      ))}

CodePudding user response:

These other answers are fine, but to ensure every key is unique do not use a numerical key. It's better to use a combination of text and numbers for your keys or, even better, a short id - https://www.npmjs.com/package/shortid

<Note
  key={`note-${note.id}`}
  id={note.id}
  title={note.title}
/>

https://reactjs.org/docs/lists-and-keys.html#keys

  • Related