Live data from Hacker News

Advice on JSX Conditionals

thoughtspile.github.io

1–10 of 127 posts

Re: Advice on JSX Conditionals

#3
I've always found these approaches to writing conditions in JSX to be terrible. Wouldn't it be nice if JavaScript were an expression-oriented language? Then you could just write:

    {if (gallery.length) {
       
    }}
There has been a "do expressions" proposal [0] for many years, which addresses this (though it is more verbose). I hope it will be accepted some day.

[0] https://github.com/tc39/proposal-do-expressions

Re: Advice on JSX Conditionals

#4
I actually really like the nested ternaries. TypeScript understand them very well and you don't have to extract your code outside the render to start using if/else structures. They also format quite well.

Re: Advice on JSX Conditionals

#7
I've always much preferred using local variables to hold conditional fragments. Since React will safely ignore null/undefined, you can do:

  let child;
  if (someCondition) {
    child = ;
  }
  
  return (
    
      Maybe here's a child: {child}
    
  );
This lets you avoid embedding conditional logic in your (already pretty dense) JSX tree.

Re: Advice on JSX Conditionals

#9

I just avoid most of it by moving the complex conditional logic into a separate component and rendering that. I don't think I've run into many issues with this strategy, and keeps my return statements nice and clean.

I find ternaries alone to be totally adequate.
Post reply on HN