Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filter vs map reactjs and jsx

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.

like image 611
HelloWorld Avatar asked Jan 06 '18 01:01

HelloWorld


2 Answers

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} />
      );
    })
}
like image 177
Danny Delott Avatar answered Sep 28 '22 18:09

Danny Delott


There is nothing unique to React and map() or filter().

In the first example when using map() you are returning an array of React components which are rendered in the DOM. You are transforming (mapping) each plain JavaScript object in the array into a React component. As a matter of fact, you are also going to return some undefined elements in the resulting array, if the condition book.shelf === shelf is falsy. Your array may look like [<Book />, <Book />, undefined, <Book />, undefined]. That's not such a big deal, since React won't render falsy values (null or undefined elements will just be skipped).

The second example won't return the same result (an array of React components), but an array of plain JavaScript objects (of type book). This is because no matter what are you returning from the filter function, it's going to be cast to a Boolean value - true or false and that value is going to decide if the current element is going to be filtered or not. The result of your .filter() function is going to be something like this (imagine shelf === 'Science'):

Original array: [{ shelf: "Science" }, { shelf: "Thrillers" }, { shelf: "Informatics" }]
Filtered array: [{ shelf: "Science" }]

As you can see, the items in the array won't be React components (<Book />) and React won't be able to render them in the DOM, thus the error it throws.

like image 40
Tsvetan Ganev Avatar answered Sep 28 '22 18:09

Tsvetan Ganev