ElMuchacho
ElMuchacho

Reputation: 300

Render JSX-element with .map() only if certain property of source object is not null

    <h1>Trending today</h1>
    <ul>
      {this.state.trendingMovies.map((movie) => (
        <li key={movie.id}>
          <NavLink to={`/movies/${movie.id}`} className="movie-link">
            {movie.title}
          </NavLink>
        </li>
      ))}
    </ul>

Here's what I got. Right now, I am rendering the whole array - but I need to render {movie.title} is not null. Please help me with writing a ternary.

Upvotes: 0

Views: 712

Answers (2)

Yevhen Horbunkov
Yevhen Horbunkov

Reputation: 15530

Considering null/undefined/false are ignored by renderer, you may use Array.prototype.map() with short-circuited &&(which will be even more compact than ternary) to return either false or <li> JSX, based on desired condition, so you won't need to do extra loop for .filter():

{this.state.trendingMovies.map((movie) => !!movie.title && (
        <li key={movie.id}>
          <NavLink to={`/movies/${movie.id}`} className="movie-link">
            {movie.title}
          </NavLink>
        </li>
      ))}

Upvotes: 2

dave
dave

Reputation: 64657

Just filter them out first:

this.state.trendingMovies.filter(movie => movie.title).map(...

or if you really want it only if it's not null (empty string is OK):

this.state.trendingMovies.filter(movie => movie.title !== null).map(...

Upvotes: 3

Related Questions