98 points · by fagnerbrack · 4y ago · 120 comments
{(() => {
switch(state) {
case 'loading': return <Loading />;
case 'ready': return <Component />;
case 'error': return <Error error={error} />;
}
})()} 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;Now throw in long functions with multiple arguments, and all kinds of different access patterns and this ternary starts to look like a nightmare.
let x = somelongfunc(arg, blah(etc))
? value1
: some other condition
? value2
: fallback
What I usually want is pattern matching expressions, but those are not in many languages.If you're ever doing this in any language with simple if() conditions, you need to refactor anyway.
Maybe, but sonarqube doesn't like it, which means I can't pass the CI pipeline, so...
return isA ? A
: isB ? B
: isC ? C
: D return isA && A || isB && B || isC && C || D;
Am I weird?If you don’t like your conditional logic in your template just give them a name and explicit boolean type and be done with it.
Still a useful overview of common idioms though for people who just get started.
I agree - I just think labeling them as JSX issues is pretty disingenuous. JSX is literally just running them as standard js expressions here - which I actually find delightful: they work the same as they do in normal javascript (quirks included :D ).
The author seems to want something like ng-if="condition", and I find DSLs in this space a real abomination.
{if (gallery.length) {
<Gallery slides={gallery}>
}}
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.“{number && <JSX />} renders 0 instead of nothing. Use {number > 0 && <JSX />} instead.”
Functional JSX would look like:
const isNumber = number > 0;
{isNumber && <JSX />}
You can similarly do things like:
const isVisible = condition1 && (condition2 || condition3) || guard(props.input1);
{isVisible && <JSX />}
The functional paradigm and some basic code factoring can make quick work of conditional JSX
* It encourages JSX-specific idioms. Outside of JSX, using `&&` instead of `if` for control flow would raise eyebrows from most people, I think.
* I find it easier and faster to refactor `if` statements to `if/else` and vice versa (only requires addition or deletion of code) than to refactor `&&` to a ternary operator and vice versa (also requires modifying existing code).
* Multiple nested ternary operators almost immediately become a mess, while a series of `else if` expressions (if such a thing existed) seem perfectly readable.
Very much so, at least for me. Relying on the short-circuiting of logical operators is fine, but only when you're actually going to use the resulting value. In the case of JSX, this is relying on the fact that `false` is a valid React child which renders nothing. Not only does this result in a mistake when the `&&` expression returns something like `0` that is falsey but isn't `false`, IMO it's already pretty awkward even if you are rendering `false`. I'd honestly prefer a runtime error, just like you get if you try to render a JS object, and only support rendering null and maybe undefined as React children.
<div>
{do {
if (user) {
<Logout />
} else {
<Login />
}
}}
</div>
https://babeljs.io/docs/en/babel-plugin-proposal-do-expressi... {!!number && <Thing />}Its more obvious what it achieves just at a glance.
The special syntax for loops in SwiftUI is important, because plain-old loops are always eager. For example, if you were building building a list using a loop, it would iterate over every item up-front to generate the list's body. With the `ForEach` struct, on the other hand, you provide the block to create each item, and it can be invoked lazily as the content will appear.
<Switch fallback={<div>Not Found</div>}>
<Match when={state.route === "home"}>
<Home />
</Match>
<Match when={state.route === "settings"}>
<Settings />
</Match>
</Switch>
Which doesn't seem to have an analog in the React babel-plugin[2] or standalone lib[3][1] https://www.solidjs.com/docs/latest/api#%3Cswitch%3E%2F%3Cma...
let child;
if (someCondition) {
child = <SomeComponent ... />;
}
return (
<div>
Maybe here's a child: {child}
</div>
);
This lets you avoid embedding conditional logic in your (already pretty dense) JSX tree.That's why a function can be better, at least you know that the value isn't changed somewhere unexpected.
I’ve been using this Babel plug-in found it quite intuitive
<Layout>
<Header />
{switch (page) {
case 'home': return <Home />
case 'about': return <About />
default: return <NotFound />
}}
<Footer />
</Layout> <Layout>
<Header />
{getCorrectComponent(page)}
<Footer />
</Layout>
const getCorrectComponent = (page) => {
switch (page) {
case 'home': return <Home />
case 'about': return <About />
default: return <NotFound />
}
} <Layout>
<Header />
<Content page={page} />
<Footer />
</Layout>
const Content = ({page}) => {
switch (page) {
case 'home': return <Home />
case 'about': return <About />
default: return <NotFound />
}
}Sometimes an inline switch is indeed the clearest code. The closest JS has is the do-expression proposal: { do { switch... }}
Here's a real world example if it matters…
const Grid = (gridItems) => (
<Grid>
{gridItems.map(item => (
<GridItem {...item} key={item._key} />
_}
</Grid>
)}
const GridItem = (props) => {
switch(props._type) {
case 'image': return <GridImage {...props} />
case 'video': return <GridVideo {...props} />
case 'copy': return <GridCopy {...props} />
// slideshows, 3D stuff, newsletter signup forms…
default: return <></>
}
}
… and I suppose a case could even be made for the granularity of this superfluous <GridItem /> component… but regardless this is just a minor annoyance that comes up from time to time. const gridComponent = {
image: GridImage,
video: GridVideo,
copy: GridCopy
}
const Grid = (gridItems) => (
<Grid>
{gridItems.map(item => {
const GridComponent = gridComponent[item._type]
return GridComponent ? <GridComponent {...item} key={item._key} /> : null
}}
</Grid>
)}I find funny the persistance in sidestepping a `.length > 0` at all costs.
function renderInput(props:Props) {
// Early exit if props are not as expected
if (!props.cond1) return null;
return <JSX/>;
}
Then the parent markup is much cleaner, without any conditional: {renderInput(props)} function ConditionalComponent(props: Props) {
if (!props.condition) return null
return <UnderlyingComponent {...props} />
}Not always worth it when you're just trying to do some conditional logic next to the code/components that it's related to.
Ideally we have the tools to decide when to add indirection ourselves instead being forced to do it to deal with complexity. You could also see this in callback-hell when we'd flatten callback trees with indirection—the tree looked flatter in the editor but we just moved code around. async/await gave us the tools to decide when we actually wanted it.
{renderIf(foo)}
<RenderIf foo={foo} />
The latter is a bit more verbose, sure, but it’s both more idiomatic and a better optimization target.I will say I've found that using prettier makes nested ternaries much more readable.
I couldn't imagine using them without prettier, but since every app I work on these days uses prettier nested ternaries aren't so bad.
I don't think I've run into many issues with this strategy, and keeps my return statements nice and clean.
It's a balance. Extracting logic into new components (and often new files!) isn't exactly ergonomic either.
I've found it's better to decrease readability if it makes understanding the logic more straight-forward (i.e. not hunting through several files to exhaust all possible outputs).
This involves people writing giant blocks of JSX that are hard to read. Especially with && all over the place. Just split up your component into smaller components with max one conditional each.
Related, can anyone tell me the origins of the bizarre react practice of one file per component? I'm assume some mega corp told people it was "best practice", but the end result is way too many files with hard to read components.
I'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
To me it boils down to one JS problem: Lacking `if` expression, and one React problem: Side effects of un/mounting.
sidenote - I discovered vladimirs blog a while back and love it. high quality content