Home > database >  Add ternary operator instead condition
Add ternary operator instead condition

Time:06-24

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

CodePudding user response:

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

CodePudding user response:

what about:

Boolean(suggestedTags.length) && (<yourElement/>)

I don't see the need for a ternary unless you have to render something if the length ends up being 0.

  • Related