Advice on JSX Conditionals
thoughtspile.github.io
Advice on JSX Conditionals
1–10 of 127 posts
Re: Advice on JSX Conditionals
#2It doesn’t necessarily have the same benefits in React, but folks ought to consider using components for control flow, like SolidJS does[1].
Re: Advice on JSX Conditionals
#3I'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.Re: Advice on JSX Conditionals
#4I 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
#5Thanks, this is really useful.
I’ve been using this Babel plug-in found it quite intuitive
Re: Advice on JSX Conditionals
#6I've learnt most of those the hard way, event though TSX is a great safe guard because I tend to slip.
I find funny the persistance in sidestepping a `.length > 0` at all costs.
Re: Advice on JSX Conditionals
#7I'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
#8I 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.
Re: Advice on JSX Conditionals
#9I 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.
Re: Advice on JSX Conditionals
#10its rare but im ok with a nested ternary when its being passed down as a prop. dont wanna use a function in that situation.
sidenote - I discovered vladimirs blog a while back and love it. high quality content