Hacker News new | past | comments | ask | show | jobs | submit login

Plus, the power of being able to treat JSX as any other JS object means that you can use standard JS constructs like loops - slightly contrived example:

  const items = [];
  let runningTotal = 0;
  for (const item of someArray) {
    runningTotal += item;
    items.push(<li>Item {item}; running total {runningTotal}</li>);
  }
  return (<ul>{items}</ul>);
The closest example I can find in Vue would require a computed property to implement something like this.



Disagree. I would argue your example is hard to read compared to the equivalent in Vue, and it mixes business logic (computing the running total) with the rendering logic.

  <script setup>
    const items = [1,2,3,4,5,6]
    let runningTotal = 0

    const getRunningTotal = (item) => {
      runningTotal += item
      return runningTotal
    }
  </script>

  <template>
    <ul>
      <li v-for="item in items">
        Item {{item}}; running total {{ getRunningTotal(item) }}
      </li>
    </ul>
  </template>
No need for a computed property. Plus, getRunningTotal can be unit tested, or extracted to another file for reusability.


You've still mixed the logic, just in a horrendously oblique manner. If you rendered the list twice the second list's running totals would be wrong from re-use of the global variable (in what is meant to be render-only logic).

If you're after keeping the concerns separate you would need to precompute the running total for each item.

See also: mustache(5) which completely embodies this philosophy.


Extracting function to separate fine in react would be equally easy . You just extract and import it.

It is just that above example is so short and readable, that you don't have to bother.


Does syntax highlighting or lsp stuff work for things like v-for?


Yep. There's a vscode extension.


I don't think this is a good way to build JSX from lists. Better to keep components smaller. Also this way will show React linting rules, like the "key" requirement.

  return (
    <ul>
      {someArray.map((item, idx) => (
         <li key={item.id}>Item {item}; running total {idx + 1}</li>
      )}
    </ul>
  );


It's technically possible, but it looks horrible and should be avoided because of lack of readability. Keep the templates plain and simple, and store your business logic elsewhere.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: