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

3
  • 2
    Don't you need to remove the curly brackets from the body of the .map() callback?
    – VLAZ
    Commented Feb 16, 2021 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 Commented Feb 16, 2021 at 18:38
  • @VLAZ you should post this, so i can check it as the accepted answer. Commented Feb 16, 2021 at 18:41

2 Answers 2

4

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

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>;
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.