Danko
Danko

Reputation: 57

Render elements from array, which depend on whether the object has certain fields

  <div className='row__posters'>
    {movies.map((movie) => (
      <img
        key={movie.id}
        onClick={() => handleClick(movie)}
        className={`row__poster ${isLargeRow && 'row__poster_big'}`}
        src={`${base_url}${
          isLargeRow ? movie.poster_path : movie.backdrop_path
        }`}
        alt={movie.title}
      />
    ))}

Ok i need render movie with only movie.poster_path and movie.backdrop_path fields to prevent mistakes u can see on pic Dominic Toretto Family. Any ideas?

Upvotes: 0

Views: 54

Answers (2)

Sanoodia
Sanoodia

Reputation: 905

Just add check before you DOM img element like this

  <div className='row__posters'>
    {movies.map((movie) => 
      (movie.poster_path && movie.backdrop_path)?
      <img
        key={movie.id}
        onClick={() => handleClick(movie)}
        className={`row__poster ${isLargeRow && 'row__poster_big'}`}
        src={`${base_url}${
          isLargeRow ? movie.poster_path : movie.backdrop_path
        }`}
        alt={movie.title}
      />
       :null
    )}

Upvotes: 1

Matthew Kwong
Matthew Kwong

Reputation: 2947

Just filter out the movies that do not have poster_path and backdrop_path before you render them.

<div className='row__posters'>
  {movies
    /* 
     * only keep movies that have both poster_path and backdrop_path
     * You may want to change this to OR condition depending on your logic
     */
    .filter(({ poster_path, backdrop_path }) => poster_path && backdrop_path)
    .map(movie => (
      <img
        key={movie.id}
        onClick={() => handleClick(movie)}
        className={`row__poster ${isLargeRow && 'row__poster_big'}`}
        src={`${base_url}${isLargeRow ? movie.poster_path : movie.backdrop_path
          }`}
        alt={movie.title}
      />
    ))}
</div>

Upvotes: 1

Related Questions