Skip to content
Advertisement

Add ternary operator instead condition

I would like to add a ternary operator to this code.

 {suggestedTags.length > 0 && (
      <div className={classes.tagSuggestionWrapper}>
        {suggestedTags.map((tag) => {
          return (<div key={tag} 
                       className={classes.tagSuggestion} 
                       onClick={() => { selectTag(tag) }}>{tag}</div>
                       );            
        })}
      </div>
    )}

I’ll explain why: I don’t need to check > 0 manually because any length more than 0 will be true

Advertisement

Answer

The code below uses ternary:

${suggestedTags.length > 0 ? (
      <div className={classes.tagSuggestionWrapper}>
        {suggestedTags.map((tag) => {
          return (<div key={tag} 
                       className={classes.tagSuggestion} 
                       onClick={() => { selectTag(tag) }}>{tag}</div>
                       );            
        })}
      </div>
    ) : ''}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement