How do I get to a nested array in React Native? - react-native

I'm trying to get to the nested array and more specifically to the "dishes" array through the map () method, but to no avail.
const RESTAURANTS = [
{
id: "1",
name: "Filada Family bar",
type: "Bakery",
rating: "5.0",
favorite: true,
hotOffer: true,
hotOfferPromo: require("../images/offers/offer_1.png"),
dishes: [
{
id: "1",
name: "Filada Family bar",
category: "cake",
type: "Asian food",
rating: "5.0",
distance: "0.2 km - $$ -",
image: require("../images/restaurants/restaurant_1.jpg"),
},
],
},
];
I usually only use the following code for the first array, but I need the data from the "dishes" array.
{RESTAURANTS.map((item) => (
<View key={item.id}>
<Text>{item.name}</Text>
</View>
))}

that is just plain javascript. You can either loop restaurants and get dishes or access a restaurant by the index in the array and get the result (or maybe search, filter whatever you need.)
access and index and the dishes property on the object:
{RESTAURANTS[0].dishes.map((item) => (
<View key={item.id}>
<Text>{item.name}</Text>
</View>
))}
Looping restaurants:
{RESTAURANTS.map((restaurant) => {
return restaurant.dishes.map((dish) => (
<View key={dish.id}>
<Text>{dish.name}</Text>
</View>
))
})}
What you need to understand here is that you have an array of objects. When mapping, the item variable means one of these objects that are being looped through and you can access any property like you would in a regular object.

Related

React Native: How to implement 2 columns of swipping cards?

I am trying to implement a scrollable list of cards in 2 columns. The cards should be swipe-able left or right out of the screen to be removed.
Basically, it should be like how the Chrome app is showing the list of tabs currently, which can be swiped away to be closed. See example image here.
I am able to implement the list of cards in 2 columns using FlatList. However, I have trouble making the cards swipe-able. I tried react-tinder-card but it cannot restrict swiping up and down and hence the list becomes not scrollable. react-native-deck-swiper also does not work well with list.
Any help is appreciated. Thank you!
I am going to implement a component that satisfies the following requirements:
Create a two column FlatList whose items are your cards.
Implement a gesture handling that recognizes swipeLeft and swipeRight actions which will remove the card that was swiped.
The swipe actions should be animated, meaning we have some kind of drag of the screen behavior.
I will use the basic react-native FlatList with numColumns={2} and react-native-swipe-list-view to handle swipeLeftand swipeRight actions as well as the desired animations.
I will implement a fire and forget action, thus after removing an item, it is gone forever. We will implement a restore mechanism later if we want to be able to restore removed items.
My initial implementation works as follows:
Create a FlatList with numColumns={2} and some additional dummy styling to add some margins.
Create state using useState which holds an array of objects that represent our cards.
Implement a function that removes an item from the state provided an id.
Wrap the item to be rendered in a SwipeRow.
Pass the removeItem function to the swipeGestureEnded prop.
import React, { useState } from "react"
import { FlatList, SafeAreaView, Text, View } from "react-native"
import { SwipeRow } from "react-native-swipe-list-view"
const data = [
{
id: "0",
title: "Title 1",
},
{
id: "1",
title: "Title 2",
},
{
id: "2",
title: "Title 3",
},
{
id: "3",
title: "Title 4",
},
{
id: "4",
title: "Title 5",
},
{
id: "5",
title: "Title 6",
},
{
id: "6",
title: "Title 7",
},
{
id: "7",
title: "Title 8",
},
]
export function Test() {
const [cards, setCards] = useState(data)
const [removed, setRemoved] = useState([])
function removeItem(id) {
let previous = [...cards]
let itemToRemove = previous.find((x) => x.id === id)
setCards(previous.filter((c) => c.id !== id))
setRemoved([...removed, itemToRemove])
}
return (
<SafeAreaView style={{ margin: 20 }}>
<FlatList
data={cards}
numColumns={2}
keyExtractor={(item) => item.id}
renderItem={({ index, item }) => (
<SwipeRow swipeGestureEnded={() => removeItem(item.id)}>
<View />
<View style={{ margin: 20, borderWidth: 1, padding: 20 }}>
<Text>{item.title}</Text>
</View>
</SwipeRow>
)}
/>
</SafeAreaView>
)
}
Notice that we need some kind of property in our objects in order to determine which one we want to remove. I have used a basic id property here, which is quite common using FlatList. If you are retrieving your data from an API which does not provide the same id, then we could just do some preprocessing (normalization) first and add the id prop ourselves.
The initial view looks as follows.
Swiping, let's say the item with 'Title 6' to the right or to the left removes it.
It might be desired to implement the following feature as well.
If the item is in the first column, then only swiping to the left will remove the item.
If the item is in the second column, then only swiping to the right will remove the item.
This is easily implemented using the index param which is passed to the renderItem function and the vx prop of the gestureState passed to the swipeGestureEnded function.
Here is fully working implementation.
import React, { useState } from "react"
import { FlatList, SafeAreaView, Text, View } from "react-native"
import { SwipeRow } from "react-native-swipe-list-view"
const data = [
{
id: "0",
title: "Title 1",
},
{
id: "1",
title: "Title 2",
},
{
id: "2",
title: "Title 3",
},
{
id: "3",
title: "Title 4",
},
{
id: "4",
title: "Title 5",
},
{
id: "5",
title: "Title 6",
},
{
id: "6",
title: "Title 7",
},
{
id: "7",
title: "Title 8",
},
]
export function Test() {
const [cards, setCards] = useState(data)
const [removed, setRemoved] = useState([])
function removeItem(id) {
let previous = [...cards]
let itemToRemove = previous.find((x) => x.id === id)
setCards(previous.filter((c) => c.id !== id))
setRemoved([...removed, itemToRemove])
}
return (
<SafeAreaView style={{ margin: 20 }}>
<FlatList
data={cards}
numColumns={2}
keyExtractor={(item) => item.id}
renderItem={({ index, item }) => (
<SwipeRow
swipeGestureEnded={(key, event) => {
if (event.gestureState.vx < 0) {
if (index % 2 === 0) {
removeItem(item.id)
}
} else if (event.gestureState.vx >= 0) {
if (index % 2 === 1) {
removeItem(item.id)
}
}
}}
disableLeftSwipe={index % 2 === 1}
disableRightSwipe={index % 2 === 0}>
<View />
<View style={{ margin: 20, borderWidth: 1, padding: 20 }}>
<Text>{item.title}</Text>
</View>
</SwipeRow>
)}
/>
</SafeAreaView>
)
}
Since the index is zero based in a FlatList, an item is in the second column if and only if index % 2 === 1 (e.g. an item with index 3 is always in the second column and thus not divisible by 2), on the other hand an item is in the first column if and only if index % 2 === 0 that is index is divisible by 2.
There are several callback function props in the SwipeRowComponent that should be fired in certain situations. However, most of them did not work in my setup and I still have no clue why. I got it to work by using the event.gestureState.vx property which is negative if we swipe to the left and positive (including zero) if we swipe to the right.
It might be desired to implement an undo button as it is quite common in this kind of functionalities. This can be done as follows:
Implement a second state which represents a Queue that holds lastly removed items. The undo button then just pops the lastly removed item.
Here is a fully working implementation with a dummy undo button that achieves exactly that.
import React, { useState } from "react"
import { Button, FlatList, SafeAreaView, Text, View } from "react-native"
import { SwipeRow } from "react-native-swipe-list-view"
const data = [
{
id: "0",
title: "Title 1",
},
{
id: "1",
title: "Title 2",
},
{
id: "2",
title: "Title 3",
},
{
id: "3",
title: "Title 4",
},
{
id: "4",
title: "Title 5",
},
{
id: "5",
title: "Title 6",
},
{
id: "6",
title: "Title 7",
},
{
id: "7",
title: "Title 8",
},
]
export function Test() {
const [cards, setCards] = useState(data)
const [removed, setRemoved] = useState([])
function removeItem(id) {
let previous = [...cards]
let itemToRemove = previous.find((x) => x.id === id)
setCards(previous.filter((c) => c.id !== id))
setRemoved([...removed, itemToRemove])
}
function undoRemove() {
if (removed && removed.length > 0) {
let itemToUndo = removed[removed.length - 1]
setCards([...cards, itemToUndo])
setRemoved(removed.filter((c) => c.id !== itemToUndo.id))
}
}
return (
<SafeAreaView style={{ margin: 20 }}>
<FlatList
data={cards}
numColumns={2}
keyExtractor={(item) => item.id}
renderItem={({ index, item }) => (
<SwipeRow
swipeGestureEnded={(key, event) => {
if (event.gestureState.vx < 0) {
if (index % 2 === 0) {
removeItem(item.id)
}
} else if (event.gestureState.vx >= 0) {
if (index % 2 === 1) {
removeItem(item.id)
}
}
}}
disableLeftSwipe={index % 2 === 1}
disableRightSwipe={index % 2 === 0}>
<View />
<View style={{ margin: 20, borderWidth: 1, padding: 20 }}>
<Text>{item.title}</Text>
</View>
</SwipeRow>
)}
/>
<Button onPress={undoRemove} title="Undo" />
</SafeAreaView>
)
}
Notice that my undo button just appends the removed item to the end of the list. If you want to keep the initial index, then you need to save the old index and push the item to the correct position.
Here is workin snack of my last implementation.

How to use nested flatlist or sectionlist?

I'm trying to create nested flatlist but an error occurres while rendering. I couldn't see any mistake. My array is like (contains semesters and lectures in that semester)
Array [
Object {
"semester": "1",
"lectures": Array [
Object {
"grade": "BA",
"id": 0,
"lecture": "TÜRK DİLİ",
},
Object {
"grade": "DC",
"id": 2,
"lecture": "FIZIKI",
},
Object {
"grade": "AA",
"id": 4,
"lecture": "BİLGİSAYAR MÜHENDİSLİĞİNE GİRİŞ",
},
Object {
"grade": "BB",
"id": 6,
"lecture": "MATEMATIKI Zorunlu сс 6 İNGİLİZCE",
},
Object {
"grade": "DD",
"id": 8,
"lecture": "NESNEYE DAYALI PROGRAMLAMA",
},
Object {
"grade": "AA",
"id": 10,
"lecture": "WEB TEKNOLOJİLERİ",
},
],
},
]
And my flatlist component:
<FlatList
data={transcript}
renderItem={({ item }) => (
<View>
<Text>{item.semester}</Text>
<FlatList
data={item.lectures}
renderItem={({ item2 }) => (
<View>
<Text>{item2.lecture}</Text>
</View>
)}
keyExtractor={(item2) => item2.id.toString()}
/>
</View>
)}
keyExtractor={(item) => item.semester.toString()}
/>
Error that I get:
[Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'item2.lecture')]
Anyway, <Text>HEY</Text> instead of <Text>{item2.lecture}</Text> works like expected.
When I use sectionlist like this
<SectionList
sections={transcript}
renderItem={({ item }) => <Text> {item.lecture}</Text>}
renderSectionHeader={({ section }) => <Text>{section.semester}</Text>}
keyExtractor={(item, index) => index}
/>
I get error
TypeError: undefined is not an object (evaluating 'items.length')
The issue here is that as per the official documentation the renderItem passes an object with three properties to the function - item, index, seperators. In the above code you are trying to de-structure a property called item2 which does not exist in the object as that property name is item.
So to keep separate name for both the renderItem methods you can rename the second item to item2 using this syntax:
renderItem={({ item: item2 })=>{}}
This will allow you to rename the property to item2 and it will work fine. You can further read about renaming destructured variable here Renaming de-structured Variable

Section List not displaying

Following the React-Native tutorial and I'm unable to get the data to show.
When I do a console.log my data appears like so:
Array [
Object {
"data": Object {
"address": "8753 2nd Street",
"id": "5507",
"inspection_date": "2019-03-27",
"inspection_time": "07:00:00",
"inspection_time_display": "07.00 AM",
"inspector": "Frank",
},
"key": "5507",
"title": "8753 2nd Street",
},
Object {
"data": Object {
"address": "11445 Paramount ave ",
"id": "5505",
"inspection_date": "2019-03-23",
"inspection_time": "10:30:00",
"inspection_time_display": "10.30 AM",
"inspector": "Fabian Hernandez",
},
"key": "5505",
"title": "11445 Paramount ave ",
},
]
I have the "data" and "title" sections as indicated in most tutorials.
My component is like this:
<Container>
<Header />
<Content>
<SectionList
renderItem={({item, index, section}) => <Text key={index}>{item}</Text>}
renderSectionHeader={({section: {title}}) => (
<Text style={{fontWeight: 'bold'}}>{title}</Text>
)}
sections={this.state.dataSource}
keyExtractor={(item, index) => item + index}
/>
</Content>
</Container>
This is what I think is happening but I'm obviously wrong since something isn't adding up.
Looping through "sections"
renderItem={({item, index, section}) => <Text key={index}>{item}</Text>}
I'm expecting this above to get the "data".
Getting title:
renderSectionHeader={({section: {title}}) => (
<Text style={{fontWeight: 'bold'}}>{title}</Text>
)}
I'm expecting this above to get the "title". What am I missing or doing wrong?
I believe the data key in each of your section objects need to be an array unto itself. Example:
const mySectionedData = [
{
title: 'section 1',
data: [
{address: '123 street', name: 'me'},
{address: '456 street', name: 'you}
]
},
{
title: 'section 2',
data: [
{address: '789 street', name: 'us'}
]
}
]
This then lets you access {title, data} from each of your sections which allows the section list to then render your section header from title, and a list of items from the data array.
Hope that helps!

Pass a couple of values in RadioGroup

Used react-native-flexi-radio-button https://github.com/thegamenicorus/react-native-flexi-radio-button for radio buttons which is awesome but wondering if other values can be passed like index and value props.
For instance Here we can get the selected index and selected value. But I wonder whether I can pass other props (like id from json below) to the radioGroup as well too. I want to pass the id as well. How can I do that?
onSelect(index, value) {
console.log('selected index and value', index + value);
}
<View style={styles.border}>
<RadioGroup
onSelect={(index, value) => this.onSelect(index, value)}
>
{this.state.foodList.map(item1 => {
return (
<RadioButton value={item1.food}>
<Text>{item1.food}</Text>
</RadioButton>
);
})}
</RadioGroup>
</View>
Json data
{"foodList": [
{
"id": 40,
"food": "Bagels",
},
{
"id": 27,
"food": "Beverage",
},
{
"id": 5,
"food": "Burger",
}
]}

React Native - Map function inside of another map function?

I have this array of data that have 4 objects, and after selecting manually one of this, I don't know how to get all the information inside. For example I want all the data that is inside 'pois' (another array)...I was thinking that should be something like this:
{api.monuments.map((monumento, index) => (
{monumento.pois.map((poi, index2) => (
<TouchableHighlight
onPress={() => this.onClick(convento)}
style={styles.monumentoContainer}
key={index2}
>
<Image style={styles.monumentoPic} source={{uri:'http://192.168.56.1:3000/'+poi.image}}>
<View style={styles.monumentoTitleContainer}>
<Text style={styles.monumentoTitle}>{poi.name}</Text>
</View>
</Image>
</TouchableHighlight>
))}
))}
But it's not - image of the error, so how can I do it?
Another question is: since I have an array with 4 objects, and each one have a specific category, how can I select only the object that have the 'category' == 'xxxxx'?
Hope you can help me! Thank you
You can do it as follows:
var api = [
{
category: "Cat_name",
monuments: [
{
item: 'item1',
pois: [
{name: 'poi1'},
{name: 'poi2'},
{name: 'poi3'},
{name: 'poi4'}
]
}
]
},
{
category: "Cat_name1",
monuments: [
{
item: 'item2',
pois: [
{name: 'poi5'},
{name: 'poi6'},
{name: 'poi7'},
{name: 'poi8'}
]
}
]
}
]
To get all pois you can do something as follows:
{api.map(i => i.monuments.map(j => j.pois.map(k => k.name)))}
And if you want to check for category name you can do something like:
{data.map(i => {
if (i.category === "Cat_name1"){
return i.monuments.map(j => j.pois.map(k => k.name))
}
})}
Here is fiddle.