I'm trying to loop through a nested array in my React native app.
I tried using a for loop, but that didn't work. I am still new to React so I'm not that familiar with how to loop
Now what I'm trying to do is to only display the data from newRow
in each object from the row
array
using { item.newRow[0].name }
does work I want to loop trough newRow
to display all the newRows
How can I loop through all the rows and get all newRows
to be displayed?
Example array:
{
id: 0,
text: 'View',
newRow: [
{id: 0, text: 'View'},
{id: 1, text: 'Text'},
{id: 2, text: 'Image'},
{id: 3, text: 'ScrollView'},
{id: 4, text: 'ListView'},
]
},
{id: 1, text: 'Text',
newRow: [
{id: 0, text: 'View'},
{id: 1, text: 'Text'},
{id: 2, text: 'Image'},
{id: 3, text: 'ScrollView'},
{id: 4, text: 'ListView'},
]
},
{id: 2, text: 'Image'},
{id: 3, text: 'ScrollView'},
{id: 4, text: 'ListView'},
Example Code:
import React, { Component } from 'react';
import { FlatList, Text, StyleSheet,View } from 'react-native';
const rows = [
{
id: 0,
text: 'View',
newRow: [
{id: 0, text: 'View'},
{id: 1, text: 'Text'},
{id: 2, text: 'Image'},
{id: 3, text: 'ScrollView'},
{id: 4, text: 'ListView'},
]
},
{id: 1, text: 'Text',
newRow: [
{id: 0, text: 'View'},
{id: 1, text: 'Text'},
{id: 2, text: 'Image'},
{id: 3, text: 'ScrollView'},
{id: 4, text: 'ListView'},
]
},
{id: 2, text: 'Image'},
{id: 3, text: 'ScrollView'},
{id: 4, text: 'ListView'},
]
// const rowsNewRow = rows[i].newRow
const extractKey = ({newRow}) => newRow
export default class App extends Component {
renderItem = ({item}) => {
return (
<Text style={styles.row}>
{item.text}
</Text>
)
}
renderLoop = ({item}) => {
var items= [];
for(let i = 0; i < item; i++){
items.push(
<View key = {i}>
<View>
<Text style={styles.row}>
{item.text}
</Text>
</View>
<View>
</View>
<View>
</View>
</View>
)
}
}
render(
) {
return (
<View style={styles.container}>
<FlatList
style={styles.container}
data={rows}
renderItem={this.renderItem}
keyExtractor={extractKey}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
marginTop: 20,
flex: 1,
},
row: {
padding: 15,
marginBottom: 5,
backgroundColor: 'skyblue',
},
})
Example App
It sounds like you are looking at including the items from your newRow array inside the row that you are creating in your FlatList.
This can be achieved by updating your renderItem
function to something like this
renderItem = ({item}) => {
let items = [];
if( item.newRow) {
items = item.newRow.map(row => {
return <Text>{row.text}</Text>
})
}
return (
<View>
<Text style={styles.row}>
{item.text}
</Text>
{items}
</View>
)
}
What I am doing is
newRow
itemsnewRow
array existsHere is a snack with the working code https://snack.expo.io/@andypandy/flatlist-with-nested-array
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With