0

I have an array and want to display each item. But map funtion does not work.

export default function SearchField() {

const renderResults = () => {
  console.log('array: ', array); // array is consoled
  return array.map(element => {
    console.log('element', element); // nothing is consoled
    return true;
  });
};

  return (
    <div>{renderResults()}</div>
  );
}

Here is my array. It is being consoled. But its elements are not mapping and consoling.

array is consoled

vytaute
  • 1,260
  • 4
  • 16
  • 36

3 Answers3

0
export default function SearchField() {
  const [searchResult, setSearchResult] = useState([]);

  const handleSearch = e => {
    setSearchResult(search.elementsFound(e.target.value));
  };

  const renderResults = () => {
      console.log('searchResult', searchResult); // searchResult array is fine here

      // does not work
      searchResult.forEach(element => {
        console.log('element', element);
      });

      // also does not work
      return searchResult.map(item => {
        console.log('res', searchResult);

         return (
          <div>{item.title}</div>
         );
     });
  }

  return (
    <div>
      <input placeholder="search..." onInput={handleSearch} />
      {renderResults()}
    </div>
  );
}

You need to return the results from .map.

TKoL
  • 13,158
  • 3
  • 39
  • 73
0

only you forgot to add curly brackets

  const renderResults = () => {
  console.log('searchResult', searchResult); // searchResult array is fine here

  searchResult.forEach(element => {
    console.log('element', element);
  });

  searchResult.map(item => {
    console.log('res', searchResult);

   return (
     <div>{item.title}</div>
    );
   });
 }
niks
  • 426
  • 4
  • 9
0

¿Are you sure it is being consoled? because array isn't log in the console

  • Well, I am sure. I added a picture btw. And I set my array earlier in the program I just didnt wanted to add uneccessary info to question. But the point is that array is consoled (shown in picture) but its elements are not. Weird, right? – vytaute Feb 24 '20 at 17:28
  • Jm but actually in the picture it looks you called the variable but not as consoled because the console must say "array: " also since you write this console.log('array: ', array); – Juan Sebastian Prieto Bustaman Feb 24 '20 at 17:32