0
 <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.

1
  • 1
    You could either return null from the map function when you do not wish to render anything, or subset the array before the map function using the filter function. Commented Jul 27, 2020 at 21:55

2 Answers 2

3

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(... 
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.