Home > Software design >  What should I use as a key for "row" elements in react?
What should I use as a key for "row" elements in react?

Time:03-18

I have a gallery that displays a number of books per row. This gallery takes an array of books as a prop and uses "itemsPerRow" prop to chunk the books into a 2 dimensional array and then loops through all the books to display the books in a grid-like structure.

export default function Gallery({ items, itemsPerRow, renderLink }) {

    itemsPerRow = itemsPerRow ?? 3
    const rows = chunk(items, itemsPerRow)

    const renderEmptyItems = (itemsToRender) => {
        const items = []
        for(let n = itemsToRender; n > 0; n--) {
            items.push(<GalleryItem key={`empty_${n}`} empty/>)
        }

        return items
    }

    return (
        <div>
        {
            rows.map((row, index) => (
                <div key={index} className="tile is-ancestor">

                    {row.map(item => <GalleryItem key={item.id} renderLink={renderLink} {...item}/>)}

                    {/* Add empty gallery items to make rows even */}
                    {index   1 === rows.length && renderEmptyItems(itemsPerRow - row.length)}
                </div>
            ))
        }
        </div>
    )
}

However, unless I give each div representing a row a key, react complains about the lack of keys. As I understand it, using the index as a key doesn't really help react and should be avoided. So what should I use as a key here <div key={index} className="tile is-ancestor"> instead of the index?

CodePudding user response:

Use a unique identifier (book.id, maybe book.title if it's unique) for the key props. If your data does not have a unique identifier, it's okay to use index.

CodePudding user response:

You need to specify a value that uniquely identify the item, such as the id. You can read more about keys in the documentation.

Also it is not recommended to use indexes as keys if the order of your data can change, as React relies on the keys to know which components to re-render, the documentation I linked explains that further.

CodePudding user response:

You can use the unique_identifier which differentiate each of the documents(probably, you should pass the document _id as a key prop in the row components)

 <div className="row">
      {notes.map((item) => {
        return (
          <div key={note._id} className="col-md-6">
            <Component item={item} />
          </div>
        );
      })}
  </div>
  • Related