Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What should I use as a key for "row" elements in react?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading