2

I totally confused, because I have mistake in my console and I read reactjs documentation and all tips on stackoverflow, but I can't unterstand what problem is. I see list of book's titles ({item.volumeInfo.title}), but console has error.

Here is my code:

import React, { Component } from 'react';
import { connect } from 'react-redux';

class BookList extends Component {
    renderBook(mainData) {
        return(
             <ul>
                {mainData.items.map((item, i) => {
                    return <li key={i} item={item}>{item.volumeInfo.title}</li>
                    })}
             </ul>
        )
    }

    render(){
        return (
            <div className="book-row">
                <div className="book-info">
                    {this.props.book.map(this.renderBook)}
                </div>
            </div>
        );
    }
}

function mapStateToProps({book}) {
    return {book};
}

export default connect(mapStateToProps)(BookList);

It is part of API response:

{ "kind": "books#volumes", 
 "totalItems": 288, 
 "items": [ 
  {
   "kind": "books#volume",
   "id": "yXlOAQAAQBAJ",
   "etag": "CG7f2mQ+7Nk",
   "selfLink": "https://www.googleapis.com/books/v1/volumes/yXlOAQAAQBAJ",
   "volumeInfo": {
    "title": "Nineteenth Century Home Architecture of Iowa City",
    "subtitle": "A Silver Anniversary Edition"

I tried to do the next keys:

key={item.etag}, key={i}, key={item.volumeInfo.title}

but error is still here.

Please help.

Thank you so much.

Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
Valeria Shpiner
  • 1,101
  • 2
  • 15
  • 27

2 Answers2

4

Since you are mapping over book:

{this.props.book.map(this.renderBook)}

the ul also needs a key prop:

renderBook(mainData, bookIdx) {
        return(
             <ul key={bookIdx}>
                {mainData.items.map((item, i) => {
                    return <li key={i} item={item}>{item.volumeInfo.title}</li>
                    })}
             </ul>
        )
    }

This is because there will be many ul siblings and React needs to tell the difference (same as with li).

However, it is better (if possible) to use a key that is not the index of the array. So, if book and item have a unique identifier, it would be best to use that.

So, it looks like you have another array outside of the sample data you provided:

[
 { "kind": "books#volumes", 
   "totalItems": 288, 
   "items": [ 
    {
Davin Tryon
  • 66,517
  • 15
  • 143
  • 132
0

Reason is you are using two map, and assigning the key in only one, assign the key to <ul> also, because of that it is giving you the error, Try this:

renderBook(mainData, index) {
    return(
        <ul key={index}>
            {mainData.items.map((item, i) => {
                 return <li key={i} item={item}>{item.volumeInfo.title}</li>
             })}
        </ul>
      )
}
Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142