Search code examples
reactjsconditional-operator

How can I do a ternary operator inside a map with the mapping for the true condition but without the mapping for the false


I'm trying to return a table with data mapped from an api. When a condition is true I want the data to be mapped and returned but when it's false I want a message to be returned.
Here's my code :

{ability?.pokemon?.map((ap) => 
  ap.is_hidden === false ? (
    <tr key={ap.pokemon.name} className='ability_container_table_body_row'>
      (multiple td tag)
    </tr>
  ) : (
    <tr>
      <td>No pokémon has this ability</td>
    </tr>
  )
)}

The problem is that I need to map the ability.pokemon because otherwise it will only return the data for the first object of the array.
The above code is returning multiple message (one for every pokemon that doesn' check the condition) and I want it to be rendered only once.

Edit : I'm using React JS


Solution

  • let items = []
    const allHidden = ability?.pokemon?.every(ap => ap.is_hidden)
    if (allHidden) {
      // No pokemon has this ability
      items = <tr><td>No pokemon has this ability</td><tr>
    } else {
     // ... map all visible ones here
     items = ability?.pokemon?.map(ap => !ap.is_hidden && (
        <tr key={ap.pokemon.name} className='ability_container_table_body_row'>
          (multiple td tag)
        </tr>
      ))}
    }
    return <table>{items}</table> // return or assign items: just an example
    

    Check if every pokemon is hidden. If true, then display your "No pokemon", if not, map the visible ones.

    The every method checks if all mapped matches the condition.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every

    https://jsfiddle.net/04fz683g/1/