Earlier quoted context omitted.
You can add do-expression proposal support in .babelrc: {do { if (user) { } else { } }} https://babeljs.io/docs/en/babel-plugin-proposal-do-expressi...
Or, no need to enable anything: {user ? : }
Advice on JSX Conditionals
51–60 of 127 posts
Re: Advice on JSX Conditionals
#52When logic gets more complicated than a single ternary (e.g., handling pending/error/result state), I've found that a `useMemo` gives me the flexibility I need. It also keeps the messy logic out of the final JSX, which tends to make it read better.
I've personally rarely even needed to useMemo, I just write a function that returns the JSX I need and { myFunction() } in the functional component's return (given React).
Re: Advice on JSX Conditionals
#53Re: Advice on JSX Conditionals
#54It doesn’t necessarily have the same benefits in React, but folks ought to consider using components for control flow, like SolidJS does[1]. 1: https://www.solidjs.com/docs/latest/api#control-flow
Re: Advice on JSX Conditionals
#55Re: Advice on JSX Conditionals
#56Earlier quoted context omitted.
I've personally rarely even needed to useMemo, I just write a function that returns the JSX I need and { myFunction() } in the functional component's return (given React).
If you're using Typescript that can get a bit annoying, since you'll also need to pass in whatever props necessary for the function to handle the logic + type them. Makes it nice and easy to test in isolation though.
Re: Advice on JSX Conditionals
#57I've only seen it used in projects once or twice but it really does wonders for readability once the team becomes OK with the new-ish syntax
Re: Advice on JSX Conditionals
#58I'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
#59Hard disagree on nested ternaries, or rather chained ternaries, which are just as easy to read and reason about as chained if else statements: if (isA) { return A; } else if (isB) { return B; } else if (isC) { return C; } else { return D; } is equivalent to return isA ? A : isB ? B : isC ? C : D;
If you're ever doing this in any language with simple if() conditions, you need to refactor anyway.
Re: Advice on JSX Conditionals
#60 {(() => {
switch(state) {
case 'loading': return ;
case 'ready': return ;
case 'error': return ;
}
})()}