skip to Main Content

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.)

2

Answers


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

    return condition && value;
    
    Login or Signup to reply.
  2. It will work

    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)}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search