Hacker News new | ask | show | jobs
by lucideer 1472 days ago
> you can write code in the template

If this is undesirable as a feature, then yes, JSX is not an appropriate choice. JSX is the furthest thing from logic-less templating. But that's a deliberate design decision.

> it's massively different to regular code

It's not. It's just regular code - there are no differences.

> weird subset of code

It's not weird. It's any JS expression. All JSX brackets are values, and JS statements don't have return values, so embedding a JS statement within a JSX value would serve no purpose. What would it do?

All statements in JS can be expressed as expressions directly (ternary/array methods) or indirectly (nested within a function expression), so there's no loss of functionality - it's not even really a subset in that sense.

1 comments

> It's not. It's just regular code - there are no differences.

> All statements in JS can be expressed as expressions directly (ternary/array methods) or indirectly (nested within a function expression), so there's no loss of functionality - it's not even really a subset in that sense.

Do you not see the contradiction?

Let me phrase it in a slightly different way:

Vanilla javascript assignments can be any expression.

JSX assignments (the brackets) can be any expression.

There's no weirdness nor extra limitations to JSX assignments compared to normal vanilla JS. It works exactly the same.

If you think not being able to assign JS blocks is weird you're going to have to explain to me what this piece of JS code would do:

  const val = if (x < y) { func(); }
You're just stating the difference between a statement and an expression. FYI, other languages (e.g. rust) have embraced the "everything is an expression" and it works extremely well, where JSX wouldn't be so awkward (in this aspect) and we could write something like:

    <div>{if (list?.length > 0) {
      list.map(e => {
        if (e.items.length) {
          <div>Excellent!</div>
        } else {
          <div>Not good.</div>
        }
      });
    } else {
      <div>Nothin to see.</div>
    }}</div>
Now, if you want to write this in actual JSX, you have to do this:

    <div>{(!!list && list.length) // awkward way of writing code
      ? list.map(e => {
          if (e.items?.length) { // normal way of writing code
            return <div>Excellent!</div>;
          } else {
            return <div>Not good.</div>;
          }
        })
      : <div>Nothin to see.</div>
    }</div>
Do you see the contradiction of being forced to use only expressions, only in some places? And this happens all the time. The most frequent thing we do in UI is rendering lists, so we use `.map` with "regular" code constantly, mixed with the awkward "expressions only" areas. Sure, the reason is that JavaScript is like that, but that doesn't make JSX any better.