Render Content Dynamically from an array map function in React Native
137,259
Solution 1
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
Solution 2
Try moving the lapsList
function out of your class and into your render function:
render() {
const lapsList = this.state.laps.map((data) => {
return (
<View><Text>{data.time}</Text></View>
)
})
return (
<View style={styles.container}>
<View style={styles.footer}>
<View><Text>coucou test</Text></View>
{lapsList}
</View>
</View>
)
}
Solution 3
lapsList() {
return this.state.laps.map((data) => {
return (
<View><Text>{data.time}</Text></View>
)
})
}
You forgot to return the map. this code will resolve the issue.
Author by
Xavier C.
Updated on August 02, 2022Comments
-
Xavier C. almost 2 years
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); }
}
-
Xavier C. almost 8 yearsOk thanks Nader, but could you tell me why it's better please?
-
Nader Dabit almost 8 yearsHey, wouldn't say it's better, just another way of structuring your code I guess. Either way will work as long as you return your component in map.
-
Xavier C. almost 8 yearsOk, I asked that because sometimes it takes less ressources! ;-) Btw thanks for your code!
-
Narendra Singh almost 6 yearsI want to get index of the item too, but unable to get that.
this.state.array.map((item, index) =>
. The index, I am getting from that is some object with Cyclic reference, so unable to print it as well. Any way to get index value for that?