by molf · 4y ago · 0 comments
{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.
The React framework strives for catching everything at compile-time. Runtime errors are a big no-no in web development.
If I recall correctly, rendering null is behaviorally equivalent to not rendering, in React.
<div>
{do {
if (user) {
<Logout />
} else {
<Login />
}
}}
</div>
https://babeljs.io/docs/en/babel-plugin-proposal-do-expressi... {user
? <Logout \>
: <Login \>
} { someBool && <Anything /> }
… only renders <Anything /> if someBool is true. {!!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.