Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple ternary operators inside a single .map() in React JS

I'm mapping data from an array and I want to display them only if they have a value different from null.
I have multiple objects in this array (power, accuracy, pp, ...) and I'm doing a ternary operator for every object.
Here's my code (which works fine) :

{move?.past_values?.map((mp) => 
  mp?.power !== null ? (
    <li>Before {mp?.version_group?.name} : {mp?.power}</li>
  ) : (
    null
  )
)}

When I try to do that :

mp?.power !== null ? (
    <li>Before {mp?.version_group?.name} : {mp?.power}</li>
  ) : (
    null
  )
mp?.accuracy !== null ? (
    <li>Before {mp?.version_group?.name} : {mp?.accuracy}</li>
  ) : (
    null
  )

it says that I should put "," after last parenthesis of the first ternary operator.
The problem is that I need to remap the whole array for the second ternary operator because "mp" becomes undefined.

Is there a way to have multiple ternary operators inside a single map function or do I have the map the array every time ?


1 Answers

If you refactor it in this way it should work and it is cleaner way of doing conditional rendering in react

 {move?.past_values?.map((mp) => 
        <>
            {mp?.power !== null && 
            <li>Before {mp?.version_group?.name} : {mp?.power}</li>}

            {mp?.accuracy !== null && 
            <li>Before {mp?.version_group?.name} : {mp?.accuracy}</li>} )
        </>
    }
like image 159
Evren Avatar answered Jun 07 '26 22:06

Evren