Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
33
rated 0 times [  40] [ 7]  / answers: 1 / hits: 28083  / 7 Years ago, sat, january 6, 2018, 12:00:00

I'm working on a react project to learn react.



In a component's render method, when I use .map to iterate over values and return an array of components, everything works as expected.



<ol className=books-grid>
{
books && books.map((book, index) => {
if (book.shelf === shelf) {
return (
<Book key={book && book.id ? book.id : index} changeShelf={this.props.changeShelf} book={book} />
);
}
})}
</ol>


But when I use filter:



<ol className=books-grid>
{
books && books.filter((book, index) => {
if (book.shelf === shelf) {
return (
<Book key={book && book.id ? book.id : index} changeShelf={this.props.changeShelf} book={book} />
);
}
})}
</ol>


I get the error (which I've researched)



Uncaught (in promise) Error: Objects are not valid as a React child



I don't understand why filter is throwing this error vs map? Is there something unique to react and .map? Both return an array.


More From » reactjs

 Answers
4

Array.filter does not allow you to transform the data into components. That is the job of Array.map.



You should instead filter first, then chain the map call afterward:



{              
books && books
.filter(book => book.shelf === shelf)
.map((book, index) => {
return (
<Book
key={book && book.id ? book.id : index}
changeShelf={this.props.changeShelf}
book={book} />
);
})
}


If you want to avoid a second pass over your list of books, you can return null as well, though this is less good because you're forcing React to render null when it doesn't need to do any work at all:



{              
books && books
.map((book, index) => {
if (book.shelf !== shelf) {
return null;
}
return (
<Book
key={book && book.id ? book.id : index}
changeShelf={this.props.changeShelf}
book={book} />
);
})
}

[#55534] Wednesday, January 3, 2018, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
reed

Total Points: 725
Total Questions: 85
Total Answers: 89

Location: Singapore
Member since Sat, Jul 25, 2020
4 Years ago
;