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 ?
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>} )
</>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With