Hacker News new | ask | show | jobs
by _0o6v 2546 days ago
Using JS ternaries for conditional rendering doesn't feel natural to me at all
5 comments

You 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?
Using {#if} or v-if or whatever feels even less natural -- especially when these template languages are hyped as being "logicless".
I 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

v-if feels quite natural to me, and easy to read as well.

I think it's a matter of personal taste.

You 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.
You 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.

You 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.

I know. That's what the poster didn't like so I suggested an alternative.
Ok, 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?
This 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>
maybe do-expression proposal could help https://github.com/tc39/proposal-do-expressions