3

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
  • to better understand your question: are you saying if mp?.power is null then evaluate mp?.accuracy? or are you saying if mp?.power is null or not evaluate mp?.accuracy? Commented Feb 3, 2022 at 18:45

1 Answer 1

2

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

8 Comments

Where do I put it ? Inside the map and I delete the ":(null)" or instead of the li ? So, with this method, I only need to do one mapping ?
Yes you need just one mapping if you are taking both data from move?.past_values. You can use directly this and it should work
It's still expecting a "," after the first operator
Can you share your code with codesandbox then I can see what's wrong
I found the problem. I just forgot to wrap these inside a div. Thx for the help and for taking your time to help me find a solution :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.