H
H
hateyyyy2016-03-06 19:38:44
JavaScript
hateyyyy, 2016-03-06 19:38:44

How to do a render in a loop in React?

Stupid question, but I can't solve the problem.
If there was an array it would be done like this

render() {
        return(
            <div >
                {this.props.list.map(function(city) {
                    return <div></div>
                }.bind(this))}
        </div>
        )
    }

But what if I have an interval and I want to draw the numbers in order, like this
render() {
        return(
            <div >
                for(let i = 0; i <2 ; i++) {
                    return<div>{i}</div>
                }
        </div>
        )
    }

But with for does not work, webpack swears
How is this situation solved?
Thanks in advance

Answer the question

In order to leave comments, you need to log in

4 answer(s)
N
Nikita Gushchin, 2016-03-06
@hateyyyy

You do not need to render inside the component with an interval, but redraw the component outside, passing different props.
The most simplified version:

class MyContainer extends Component {
  constructor() {
    this.state = { nums: [] }
  }
  
  componentDidMount() {
    this.intervalId = setInterval(() => {
      this.setState({
        nums: [
          ...this.state.nums,
          (this.state.nums[this.state.nums.length-1] || 0) + 1
        ],
      })
    }, 1000)
  }

  componentWillUnmount() {
    clearInterval(this.intervalId)
  }

  render() {
    retrurn (
      <div>
       {this.state.nums.map((n, i) => (<b key={i}>Number is: {n}</b>)}
      </div>
    )
  }
}

R
RubaXa, 2016-03-06
@RubaXa

render() {
  return (
    <div>
       ${Array.from({length: 5}).map((_, idx) => <div>{idx}</div>)}
    </div>
  );
}

// или

render() {
  const list = [];
  for (let idx = 0; idx < 5; idx++ ){
     list.push(<div>{idx}</div>);
  }
  return <div>${list}</div>;
}

A
Anton Izmailov, 2016-03-06
@WapGeaR

The best choice is 2 components.
Just make a parent, and next to it, place its child and display information in it. In the parent, call your child in the loop and there will be no problem. So it's more correct.

K
keslo, 2016-03-06
@keslo

Most likely, these blocks will not be empty, but with some content?
In this case, pass the newly received data to the propscomponent, and already inside it, use the mapcomponents to collect as much as necessary.
I practically talked about the example that you yourself gave as a worker.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question