Trivial else (suggestion/enhancement)
See original GitHub issueI find I have a common pattern of
<Choose>
<When condition={foo}>one-liner</When>
<Otherwise>
a lot of stuff
</Otherwise>
</Choose>
It kind of makes me want to just use a ternary; the control statements are neither succinct or clear/intent-expressive.
The one-liner in question will be a marker for “field not present”, an icon, a <NotFound/> component, and in some cases even a single space.
An alternative which I think would make sense is something like:
<SomeControlTag condition={!foo} someprop="one-liner">
a lot of stuff
</SomeControlTag>
While having jsx in props looks weird, it’s completely valid, and I’ve used it a couple of times with react-bootstrap stuff. I wouldn’t recommend it for longer values, but it’s fine for short stuff. So, you could in fact also have, someprop={<NotFound/>}
.
Now, assuming this is a good idea at all, what does the actual tag and prop look like?
My first instinct was to add this to <If>:
<If condition={!foo} else="one-liner">
The problem should be obvious though… having “else” before “then” feels really odd. But I don’t know if that objection is strong enough to justify loading the namespace with a new tag that does mostly the same thing as <If>.
Here’s a weird alternative, I don’t like but I’ll write it down anyway:
<If condition={foo} then="one-liner" else>
stuff
</If>
Anyway. Please discuss 😺
Issue Analytics
- State:
- Created 7 years ago
- Comments:7 (2 by maintainers)
Top GitHub Comments
In my opinion the succinct version would be the flat if-else.
Discussion #32
I don’t think that the deprecated Else-Syntax needs to be revived. In your suggested version it is not as readable as it should be:
<If>
and<Else>
should be on the same indentation level. The XML-way is<choose>
and works like that in XSL-T.Regarding the abbreviated syntax, you already name the counter-argument: Edge cases which make less and less sense. Additionally, one of the most prominent React arguments is: Keep the API surface as small as possible. And React really lives up to this mantra, if you think about it.
I’m also not convinced that writing
is more readable than, e.g.
From my point of view I would always expect the else branch on the same level as the if branch. I can’t imagine that users wouldn’t be confused by the abbreviated syntax…