Xavier C. Xavier C. - 6 months ago 78
Javascript Question

Render Content Dynamically from an array map function in React Native

I'm trying to get data from an array and using map function to render content. Look at

**{this.lapsList()}**


and the associated

**lapsList()**


function to understand what I'm trying to do. The result is nothing is displaying (Views under view, etc.) Here is my simplified code:

class StopWatch extends Component {

constructor(props) {
super(props);

this.state = {
laps: []
};
}

render() {
return (
<View style={styles.container}>
<View style={styles.footer}>
<View><Text>coucou test</Text></View>
{this.lapsList()}
</View>
</View>
)
}

lapsList() {

this.state.laps.map((data) => {
return (
<View><Text>{data.time}</Text></View>
)
})

}

_handlePressLap() {

console.log("press lap");

if (!this.state.isRunning) {

this.setState({
laps: []
})

return

}

let laps = this.state.laps.concat([{'time': this.state.timeElapsed}]);

this.setState({
laps: laps
})

console.log(laps);

}


}

Answer

Don't forget to return the mapped array , like:

lapsList() {

    return this.state.laps.map((data) => {
      return (
        <View><Text>{data.time}</Text></View>
      )
    })

}

Reference for the map() method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Comments