Search code examples
reactjsconditional-operator

Wrap ternary expression in React in function


In React, I often want to render something only when a condition is true. I used to do this, and it worked well:

return {condition?value:null}

Actual return expression is much more complicated, so a simple if statement would not do. But then I thought the null part was ugly, so I tried wrapping it in a function:

return {addIf(condition, value)}

Problem is, sometimes value uses what condition checks if is accessible. For example, condition would be like player.hasOwnProperty(x) and value would be player.x. This creates an error.

I think this is because value always evaluates in the latter. How can I achieve this? Is using ternary expressions with null the only way?

(I feel like what I really need is Lisp macro, but hopefully there's a much easier workaround.)


Solution

  • I think you can use the logical && operator. Your solution will look like this:

    return condition && value;