5 ms·
Using JS ternaries for conditional rendering doesn't feel natural to me at all
by _0o6v 7y ago
Using JS ternaries for conditional rendering doesn't feel natural to me at all
- yodon 7y agoOk, I should probably edit my comment to "JSX/TSX feels so incredibly natural except for needing to use JS ternaries for conditional rendering" because seriously what were they thinking there?
- steinuil 7y agoThis is more of an issue with JS than React. ReasonML also has JSX support and since `if` is an expression rather than a statement you can do this: <div> {if (cond) { <Comp1 /> } else { <Comp2 /> }} </div> Or even: <div> {switch (expr) { | A => <CompA /> | B => <CompB /> | _ => <CompC /> }} </div>
- ducaale 7y agomaybe do-expression proposal could help https://github.com/tc39/proposal-do-expressions https://github.com/tc39/proposal-do-expressions
- manigandham 7y agoYou don't have to, you can create a simple 1 line component to turn it into a declarative style. It's the benefit of having a full language instead of a template DSL for rendering. Declarative syntax is easy inside of an imperative flow, doing the opposite tends to lead to problems though.
- the_duke 7y agoYou don't need a one line component, you can just declare an extra variable before your main JSX. A redundant extra component is bad for performance.
- manigandham 7y agoI know. That's what the poster didn't like so I suggested an alternative.
- s_y_n_t_a_x 7y agoYou don't have to. The beauty of it being a simple JS function is you have flexibility. function FileList() { if (!files.length) { return <EmptyMessage/>; } return <List items={files} />; } function FileList() { return files.length ? <List items={files}/> : <EmptyMessage/>; } What feels unnatural is the syntax that these templates pull out of thin air to do things the language can already do. Why should I need to learn another syntax just for templates?
- ng12 7y agoUsing {#if} or v-if or whatever feels even less natural -- especially when these template languages are hyped as being "logicless".
- core-questions 7y agoI don't see why anyone would want a "logicless" templating language. Doesn't that sort of kill the point of it being a "language" to begin with? /me goes back to happily "server side rendering" HTML with PHP
- enraged_camel 7y agov-if feels quite natural to me, and easy to read as well. I think it's a matter of personal taste.
- simplify 7y agoYou can use short circuiting instead: <div> {items.length === 0 && <p>No items.</p> } {items.length === 1 && <p>Warning: You only have 1 item, at least 2 is required</p> } {items.map(...)} </div> `false` is not rendered by react, so this code is perfectly fine.