H
H
hulktoster2019-09-09 22:02:02
React
hulktoster, 2019-09-09 22:02:02

Why don't React developers write for, while loops?

For example, I have never seen anyone write such cycles in React code, which means they are either written very rarely or not written at all. Why is that? Does this go against the principles of react?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
H
hzzzzl, 2019-09-09
@hulktoster

hulktoster , map/filter/reduce do just what is needed in React - they convert an array with data into an array with React components, of course, you can also through cycles, but this will be more scribbling and will be less visual

data = [........]

render() {
  return (
  <>
    { data.map(x => <MyComponent prop1={x.prop1} prop2={x.prop2} />) }
  </>
  )
}

data = [........]

render() {
  const components = []
  for(let i = 0; i < data.length; i++) {
    const x = data[i]
    components.push(<MyComponent  prop1={x.prop1} prop2={x.prop2} />)
  }

  return (
  <>
    { components }
  </>
  )
}

and this is only if you need to map something, and if you still filter, etc., then there are more and more lines in the cycle

G
grinat, 2019-09-09
@grinat

It's just that React is a pretty crappy templating engine, so you have to get out. And you have not yet seen what happens if the component is tricky, you have to drink smoothies with substances in order to understand the train of thought of the predecessor.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question