I have this array, that I want to iterate. I need to delay it by a couple of seconds before the next.
{this.props.things.map((thing, index) => {
return
The render function of react is synchronous. Also javascript map is synchronous. So using timers is not the right solution here.
You can however, in your component state, keep track of items that have been rendered and update that state using javascript timers:
For an example implementation check out this fiddle:
React.createClass({
getInitialState() {
return {
renderedThings: [],
itemsRendered: 0
}
},
render() {
// Render only the items in the renderedThings array
return (
{
this.state.renderedThings.map((thing, index) => (
{thing.content}
))
}
)
},
componentDidMount() {
this.scheduleNextUpdate()
},
scheduleNextUpdate() {
this.timer = setTimeout(this.updateRenderedThings, 1000)
},
updateRenderedThings() {
const itemsRendered = this.state.itemsRendered
const updatedState = {
renderedThings: this.state.renderedThings.concat(this.props.things[this.state.itemsRendered]),
itemsRendered: itemsRendered+1
}
this.setState(updatedState)
if (updatedState.itemsRendered < this.props.things.length) {
this.scheduleNextUpdate()
}
},
componentWillUnmount() {
clearTimeout(this.timer)
}
})