Hacker News new | ask | show | jobs
by lucideer 1479 days ago
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(); }
1 comments

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.