1

I have the following code:

const displayData = (data) => {
    console.log(data);// this shows an array of objects
    if (!data.length) return null;
    
    return data.map((movie, index)=>{
       <div key={index} className="movie-display" >
            <h2>{movie.Title}</h2>
            <p>{movie.Year}</p>
        </div>
    })
}
return (
    <div className="search">
        <form >
            <input
                type="text"
                placeholder="Enter details here"
                onChange={(event) => setSearchTerm(event.target.value)}
            />
            <button type="button" onClick={() => fetchData()}>Search</button>
        </form>
        <div className="movies-list">
            {displayData(data)}
        </div>
    </div>
 );

}

And can't get data.map to work This is what that commented console.log shows in console:

enter image description here

klaus_bathory
  • 158
  • 2
  • 13
  • 2
    Don't you need to remove the curly brackets from the body of the `.map()` callback? – VLAZ Feb 16 '21 at 18:36
  • @VLAZ That fixed it. I just spent more than 5 hours on this, without even having an idea that it doesn't work if i have curly braces. Thought that was optional when i returned a single thing. Thanks a lot – klaus_bathory Feb 16 '21 at 18:38
  • @VLAZ you should post this, so i can check it as the accepted answer. – klaus_bathory Feb 16 '21 at 18:41

2 Answers2

4

Your syntax is off. You’re not returning anything inside the map function.

Michiel
  • 956
  • 2
  • 7
  • 19
2

You're not returning anything from the map() lambda. You should return the JSX from your map callback as follows:

return data.map((movie, index) => {
  return <div key={index} className="movie-display">
           <h2>{movie.Title}</h2>
           <p>{movie.Year}</p>
         </div>;
});
BenM
  • 52,573
  • 26
  • 113
  • 168