Search code examples
reactjskey

Unique key React, solution?


How to pass key in this code?

{result.map(book, key => I got stuck here. I tried several times but I can't!

          { 
             result.map(book => (
                    <div className="col-md-3 mb-5">
                        <div className="card card-body bg-light text-center h-100">
                            <img className="w-100 mb-2" src={book.volumeInfo.imageLinks !== undefined ? book.volumeInfo.imageLinks.thumbnail : ''} alt={book.title} />
                            <h3 className="text-dark card-title">{book.volumeInfo.title}</h3>
                            <h5 className="text-dark card-title">{book.volumeInfo.authors}</h5>
                            </Link>
                        </div>
                    </div>
                   ))
          }

Solution

  • The best way is to use unique key for the books (ID). It might be doing problems if you will delete the books for example.

    I don't know your API implementation but it could look something like that:

     {result.map(book => (
        <div className="col-md-3 mb-5" key={book.id}>
            <div className="card card-body bg-light text-center h-100">
                <img className="w-100 mb-2" src={book.volumeInfo.imageLinks !== undefined ? book.volumeInfo.imageLinks.thumbnail : ''} alt={book.title} />
                <h3 className="text-dark card-title">{book.volumeInfo.title}</h3>
                <h5 className="text-dark card-title">{book.volumeInfo.authors}</h5>
                </Link>
            </div>
        </div>
    ))}