1

I map my arrays via

moviesList.map(movie => <MovieCard movieID={movie} key={movie} 

but my API gives sometimes 1 or more results. How can I change my .map to show only the first result?

1
  • 3
    If you only want the first item then you likely do not want a .map at all. To get the first item you can do moviesList[0] Commented Mar 10, 2020 at 17:36

3 Answers 3

1

Try this one

[moviesList[0]].map(movie => <MovieCard movieID={movie} key={movie} 

Sign up to request clarification or add additional context in comments.

Comments

1

First of all, writing moviesList[0].map will make your loop crash if [0] is an object, because it won't be iterable. So you basically need to get rid of all objects but the first one. You can do it with slice(). Here, slice(0,1) means "take all element from 0 to 1 in the array". So only the first object will survive. Then your map() will work like a charm. Also, the key is a basic number "i", obtained from map(), which is better than passing a whole object. If you want to use an object property for a key, please use something like movie.id, and not movies as a whole.

moviesList.slice(0,1).map((movie,i)=> <<MovieCard movieID={movie} key={i}/>) 

Comments

0

Try this,

moviesList[0].map(movie=><MovieCard movieID={movie} key={movie}/> )

Or if you only want to show only one. Try this,

<MovieCard movieID={moviesList[0]} key={moviesList[0]}/>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.