Cannot read property 0 of undefined - arrays

I have tried desperately to resolve this issue but still befuddled. Getting "Cannot read property 0 of undefined" error trying to pass array gallery[] which has photos as the first (0) index.
I have verified that the array gallery does exist and in the correct format when I console.log it. However, I am not sure why 2 console statements are returned with the first one being undefined and the second one being correct.
Please see code snippets and screen capture below for details. I will appreciate your help as I am completely lost. This is the only aspect delaying completing my app dev. Thanks
<Text style={styles.sectionHeader}> Photo Galery</Text>
<View >
{console.log(gallery)}
{
<TouchableOpacity >
<Image
source={gallery[0].photos}
style={styles.navImageStyle}
/>
</TouchableOpacity>
}
Here's the screenshot with correct gallery object defined. I have tried all kinds of ways to reference it in my image tag (even using source={{uri: gallery[0].photos}} but no luck.
When I revise the image tag with source={gallery}, no images displayed at all even though I know that syntax is incomplete. See image below.
--- More detail below per request -----
The gallery array is from a local data array (placesData) that is imported by code below. The code then imports gallery as a prop in a modal window (SiteDetails) upon button press
import React, { Component } from 'react';
import { View, FlatList } from 'react-native';
import { ListItem, } from 'native-base';
import { placesData } from '../../data/placesData';
import Places from '../../data/Places';
import SiteDetails from '../SiteDetails';
export default class NavPlaces extends Component {
constructor(props) {
super(props);
this.state = {
setModalVisible: false,
modalArticleData: {},
error: null
};
}
_handleItemDataOnPress = articleData => {
this.setState({
setModalVisible: true,
modalArticleData: articleData
});
};
_handleModalClose = () => {
this.setState({
setModalVisible: false,
modalArticleData: {}
});
};
render() {
return (
<View>
<FlatList
data={placesData}
renderItem={({ item }) => (
<ListItem style={{ marginLeft: 5,}}>
<Places onPress={this._handleItemDataOnPress} data={item} />
</ListItem>
)}
horizontal={true}
keyExtractor={item => item.id}
/>
<SiteDetails
showModal={this.state.setModalVisible}
articleData={this.state.modalArticleData}
onClose={this._handleModalClose}
/>
</View>
);
}
}
SiteDetails
import React, { Component } from "react";
import Icon from "react-native-vector-icons/FontAwesome";
import {
FlatList,
Dimensions,
Modal,
ScrollView,
Share,
TouchableOpacity, Image, Text, View,
} from "react-native";
import {
Grid, Row, Col,
Header,
ListItem,
Content,
Container,
Body,
Left,
Right,
Title,
} from "native-base";
// import PlacePhoto from '../data/PlacePhoto';
// import NavGallery from "./Tabs/NavGallery";
// import {placesData} from '../data/placesData'
const webViewHeight = Dimensions.get("window").height - 56;
const deviceHeight = Dimensions.get('window').height;
const deviceWidth = Dimensions.get('window').width;
export default class SiteDetails extends Component {
constructor(props) {
super(props);
this.data = props.data;
}
_handleClose = () => {
return this.props.onClose();
};
_handleShare = (clickedLink, clickedTitle) => {
// const { link,title } = this.props.data;
message = `${clickedTitle}\n\nRead more #\n${clickedLink.toString()}\n\nshared via MSU mobile`;
return Share.share(
{ clickedTitle, message, url: message },
{ dialogTitle: `Share ${clickedTitle}` }
);
};
render() {
const { showModal, articleData } = this.props;
const { image, title, subTitle, description,location, phone, credit, gallery } = articleData;
// if (image !== undefined) {
return (
<Modal
onRequestClose={this._handleClose}
visible={showModal}
transparent
animationType="slide"
>
<Container
style={{ margin: 0, marginBottom: 0, backgroundColor: "#ffffff" }}
>
<Content contentContainerStyle={{ height: webViewHeight }}>
<Header
style={{ backgroundColor: "#1b4383" }}
iosBarStyle="light-content"
>
<Left>
<TouchableOpacity onPress={() => this._handleClose()}>
<Icon
name="close"
style={{ fontSize: 25, color: "#f47937", paddingHorizontal: 10, }}
/>
</TouchableOpacity>
</Left>
<Body>
<Title
children={title}
style={{ color: "#ffffff" }}
/>
</Body>
<Right>
<TouchableOpacity
// onPress={() =>
// this._handleShare(articleData.link, articleData.title)
// }
>
<Icon
name="share-alt"
style={{ fontSize: 30, color: "#f47937", paddingHorizontal: 10, }}
/>
</TouchableOpacity>
</Right>
</Header>
<ScrollView>
<Image
source={image}
style={styles.drawerCover}
/>
<View style={{backgroundColor: 'black', }}>
<Text style={styles.titleText}>{title}</Text>
<View style={{ height: 16 }}/>
<Text style={styles.subTitleText}>{subTitle}</Text>
<View style={{ height: 16 }}/>
<Grid>
<Row>
<Col style={{ flexDirection: 'row'}}>
<Icon
name='map-o'
style={styles.iconStyle}
/>
<Text style={styles.subText}>location:</Text>
</Col>
<Col>
<Text style={styles.subText}>{location}</Text>
</Col>
</Row>
<View style={{ height: 16 }}/>
<Row>
<Col style={{ flexDirection: 'row'}}>
<Icon
name='phone'
style={styles.iconStyle}
/>
<Text style={styles.subText}>tel:</Text>
</Col>
<Col>
<Text style={styles.subText}>{phone}</Text>
</Col>
</Row>
<View style={{ height: 16 }}/>
<Row>
<Col style={{ flexDirection: 'row'}}>
<Icon
name='globe'
style={styles.iconStyle}
/>
<Text style={styles.subText}>Website:</Text>
</Col>
<Col>
<Text style={styles.subText}></Text>
</Col>
</Row>
<View style={{ height: 16 }}/>
<Row>
<Col style={{ flexDirection: 'row'}}>
<Icon
name='pencil'
// name='creative-commons'
style={styles.iconStyle}
/>
<Text style={styles.subText}>Credit:</Text>
</Col>
<View style={{ height: 16 }}/>
<Col>
<Text style={styles.subText}>{credit}</Text>
</Col>
</Row>
</Grid>
</View>
<Text style={styles.sectionHeader}> Photo Galery</Text>
<View >
{console.log(gallery)}
{
<TouchableOpacity >
<Image
source={gallery}
style={styles.navImageStyle}
/>
</TouchableOpacity>
}
<Text style={styles.sectionHeader}> Description </Text>
<Text style={styles.bodyText}> {description} </Text>
</View>
</ScrollView>
</Content>
</Container>
</Modal>
);
// } else {
// return null;
// }
}
}
placesData array:
export const placesData =
[
{
id: 'a',
image: require('../../assets/img/places/museum/slave/slavePic.jpg'),
title: 'Slave Trade Museum',
subTitle: 'One of many rare gems of history and education',
location: 'Badagry, Lagos',
phone: '',
credit: 'The Freeman Institute',
gallery:[
{
key: 'v1',
photos: [
require('../../assets/img/places/museum/slave/abolitionCannon.jpg'),
require('../../assets/img/places/museum/slave/holdingCell.jpg'),
require('../../assets/img/places/museum/slave/slaveMarket.jpg'),
require('../../assets/img/places/museum/slave/slaveNoReturn.jpg'),
require('../../assets/img/places/museum/slave/bibleAtBadagry.jpg'),
require('../../assets/img/places/museum/slave/bridge.jpg'),
]
}
],
description: 'Excerpts from Freeman Institute',
},
{
id: 'b',
image: require('../../assets/img/places/parks/yankari.png'),
title: 'Parks and WildLife',
subTitle: 'Visit to this wildlife park will rejuvenate your mind and spirit',
location: 'Jos, Lagos, Calabar, Abuja, etc',
phone: '',
credit: 'The Freeman Institute',
gallery:[
{
id: 'v2',
photos: [
require('../../assets/img/places/parks/ikogosi.png'),
require('../../assets/img/places/parks/abujaPark.png'),
require('../../assets/img/places/parks/raindeer.png'),
require('../../assets/img/places/parks/kainji.png'),
require('../../assets/img/places/parks/elephant.png'),
require('../../assets/img/places/parks/owuH2OFalls.png'),
]
}
],
description: 'Excerpts from online wiki',
},
{
id: 'c',
image: require('../../assets/img/places/resorts/badagry.png'),
title: 'Resorts and Beaches',
subTitle: 'Simply exquisite vacation sites, peaceful and beautiful beaches. Go on horseback riding or whatever suits you.',
location: 'Lagos, Calabar, Abuja, etc',
phone: '',
credit: 'Online wiki',
gallery:[
{
id: 'v3',
photos: [
require('../../assets/img/places/resorts/funtopiaPark.png'),
require('../../assets/img/places/resorts/barBeach.png'),
require('../../assets/img/places/resorts/obudu.png'),
require('../../assets/img/places/resorts/funtopiaPark.png'),
require('../../assets/img/places/resorts/whisperingPalms.png'),
require('../../assets/img/places/resorts/tinapa.png'),
]
}
],
description: 'Excerpts from online wiki',
},
{
id: 'd',
image: require('../../assets/img/places/museum/museumBeni.png'),
title: 'National Musuems',
subTitle: 'Incredible museums of history and education with variety to enrich the minds.',
location: 'Lagos, Jos, Kaduna, Enugu, Benin, etc',
phone: '',
credit: 'Ministry of Tourism',
gallery:[
{
id: 'v4',
photos: [
require('../../assets/img/places/museum/museumLagos.jpg'),
require('../../assets/img/places/museum/museumWar.jpg'),
require('../../assets/img/places/museum/museumKaduna.jpg'),
require('../../assets/img/places/museum/museumOwo.jpg'),
require('../../assets/img/places/museum/museumColonia.jpg'),
require('../../assets/img/places/museum/museumOwo.jpg'),
]
}
],
description: 'Excerpts from online wiki',
},
]
// export const placesData =
// [
// {
// id: 'a',
// image: require('../../assets/img/places/museum/slave/slavePic.jpg'),
// title: 'Slave Trade Museum',
// subTitle: 'One of many rare gems of history and education',
// location: 'Badagry, Lagos',
// phone: '',
// credit: 'The Freeman Institute',
// photos:{
// key: 'a1',
// pic1: require('../../assets/img/places/museum/slave/abolitionCannon.jpg'),
// pic2: require('../../assets/img/places/museum/slave/holdingCell.jpg'),
// pic3: require('../../assets/img/places/museum/slave/slaveMarket.jpg'),
// pic4: require('../../assets/img/places/museum/slave/slaveNoReturn.jpg'),
// pic5: require('../../assets/img/places/museum/slave/bibleAtBadagry.jpg'),
// pic6: require('../../assets/img/places/museum/slave/bridge.jpg'),
// },
// description: 'Excerpts from Freeman Institute',
// },
// {
// id: 'b',
// image: require('../../assets/img/places/parks/yankari.png'),
// title: 'Parks and WildLife',
// subTitle: 'Visit to this wildlife park will rejuvenate your mind and spirit',
// location: 'Jos, Lagos, Calabar, Abuja, etc',
// phone: '',
// credit: 'The Freeman Institute',
// photos:{
// key: 'b1',
// pic1: require('../../assets/img/places/parks/ikogosi.png'),
// pic2: require('../../assets/img/places/parks/abujaPark.png'),
// pic3: require('../../assets/img/places/parks/raindeer.png'),
// pic4: require('../../assets/img/places/parks/kainji.png'),
// pic5: require('../../assets/img/places/parks/elephant.png'),
// pic6: require('../../assets/img/places/parks/owuH2OFalls.png'),
// },
// description: 'Excerpts from online wiki',
// },
// {
// id: 'c',
// image: require('../../assets/img/places/resorts/badagry.png'),
// title: 'Resorts and Beaches',
// subTitle: 'Simply exquisite vacation sites, peaceful and beautiful beaches. Go on horseback riding or whatever suits you.',
// location: 'Lagos, Calabar, Abuja, etc',
// phone: '',
// credit: 'Online wiki',
// photos:{
// key: 'c1',
// pic1: require('../../assets/img/places/resorts/funtopiaPark.png'),
// pic2: require('../../assets/img/places/resorts/barBeach.png'),
// pic3: require('../../assets/img/places/resorts/obudu.png'),
// pic4: require('../../assets/img/places/resorts/funtopiaPark.png'),
// pic5: require('../../assets/img/places/resorts/whisperingPalms.png'),
// pic6: require('../../assets/img/places/resorts/tinapa.png'),
// },
// description: 'Excerpts from online wiki',
// },
// {
// id: 'd',
// image: require('../../assets/img/places/museum/museumBeni.png'),
// title: 'National Musuems',
// subTitle: 'Incredible museums of history and education with variety to enrich the minds.',
// location: 'Lagos, Jos, Kaduna, Enugu, Benin, etc',
// phone: '',
// credit: 'Ministry of ?',
// photos:{
// key: 'd1',
// pic1: require('../../assets/img/places/museum/museumLagos.jpg'),
// pic2: require('../../assets/img/places/museum/museumWar.jpg'),
// pic3: require('../../assets/img/places/museum/museumKaduna.jpg'),
// pic4: require('../../assets/img/places/museum/museumOwo.jpg'),
// pic5: require('../../assets/img/places/museum/museumColonia.jpg'),
// pic6: require('../../assets/img/places/museum/museumOwo.jpg'),
// },
// description: 'Excerpts from online wiki',
// },
// ]

Related

How to get data from checkbuttons to a list in React Native?

I am a beginner with React Native, so I need help with following:
I am programming an App, where you can choose between two radio button groups. To every radio button should belong data (key and value pairs, in categories). If choose two options and afterwards press the butto "Create my plan" it should randomly choose some entries of the key value kategories and create a flatlist from it.
My problem is, that I dont know how I can pass data bewteen two classes or if there is an other way to realize what I picture.
Please do not be put off by the amount of code, if you copy it and paste it into an empty project, it works immediately and you will understand my question.
I am very grateful for your help.
Here is my Code:
import React, { Component, useState, createContext } from 'react';
import { StyleSheet, FlatList, Text, Dimensions, Button, View, Image, ScrollView, TouchableOpacity, Animated } from 'react-native';
import { registerRootComponent } from 'expo';
import { RadioButton } from 'react-native-paper';
import 'react-native-gesture-handler';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
//Ein StackNavigator-Objekt wird erzeugt
const Stack = createStackNavigator();
class Auswahl extends React.Component {
state = {
value1: 'first',
value2: 'first',
value3: 'first',
checked: 'agnostic'
};
render() {
return (
<View style={{alignItems:"center", flex:1, flexDirection:'column' }}>
<View style={{position:'absolute', alignItems:"center", flex:1, flexDirection:'column'}}>
<Text style={{ marginTop:50, marginBottom:10 }}>Auf welchem Niveau praktizierst du?</Text>
<View style={{flex: 1, flexDirection: 'column', marginBottom: 20}}>
<RadioButton.Group
onValueChange={value1 => this.setState({ value1 })}
value={this.state.value1}>
<Text>Anfgänger</Text>
<RadioButton.Android value="first" />
<Text>Geübt</Text>
<RadioButton.Android value="second" />
<Text>Eingeschränkt</Text>
<RadioButton.Android value="third" />
</RadioButton.Group>
<Text style={{ marginBottom: 10 }}>Möchtest du einen Fokus setzten?</Text>
<RadioButton.Group
onValueChange={value2 => this.setState({ value2 })}
value={this.state.value2}>
<Text>Dehnung</Text>
<RadioButton.Android value="first" />
<Text>Hüftöfner</Text>
<RadioButton.Android value="second" />
<Text>Energie</Text>
<RadioButton.Android value="third" />
</RadioButton.Group>
<Button style={{margin:10, padding:10}} title="Erstelle meinen Plan" onPress={() =>
this.props.navigation.navigate('UebungenAnzeigen') }/>
</View>
<View/>
</View>
</View>
);
}
}
class UebungenAnzeigen extends React.Component {
constructor(props){
super(props);
this.state = {
data:[
{
"name": "Herabschauender Hund",
"kategorie":"Basic",
"nummer" : "0",
"erklaerung": "Steißbein zur Decke | Rücken gerade | Kopf in Verlängerung der Wirbelsäule",
"photo": "",
"dauer": 30
},
{
"name": "Katze",
"nummer" : "2",
"erklaerung": "Steißbein zur Decke | Rücken gerade | Kopf in Verlängerung der Wirbelsäule",
"photo": "",
"dauer": 20
},
]
}
}
render() {
function Item({ item }) {
const [shouldShow, setShouldShow] = useState(true);
return (
<View style={styles.container}>
{shouldShow ? (
null
) :
<View style={stylesUebungAnzeigen.uebung}>
<Text>Details</Text>
<Text style={{marginTop: 20 }}>{item.name}</Text>
<TouchableOpacity style={{marginTop: 100, color:'green'}} onPress= {() => setShouldShow(!shouldShow)}>Zurück zur Übersicht</TouchableOpacity>
</View>
}
<View style={stylesUebungAnzeigen.listItem}>
<Image source={item.photo} style={{width:90, height:60, borderRadius:10}} />
<View style={{alignItems:"center",flex:1}}>
<Text style={{fontWeight:"bold"}}>{item.name}</Text>
<Text>{item.dauer}</Text>
</View>
<TouchableOpacity onPress={() => setShouldShow(!shouldShow)} style={{height:50,width:50,
justifyContent:"center", alignItems:"center"} }>
<Text style={{color:"green", fontWeight:"bold"}}>Hilfestellung?</Text>
</TouchableOpacity>
</View>
</View>
);
}
return (
<View>
<View style={stylesUebungAnzeigen.container2}>
<FlatList style={{flex:1}}
data={this.state.data}
renderItem={({ item }) => <Item item= {item}/>}
keyExtractor={item => item}
/>
</View>
</View>
);
}
}
const stylesUebungAnzeigen = StyleSheet.create ({
buttons: {
flex: 1,
alignSelf:"center",
height: 10,
width: 30
},
uebung:{
fex:1,
alignSelf:"center",
justifyContent:"center",
height: 911,
width: 318,
borderColor:'grey',
backgroundColor: 'white'
},
text:{
flex:1,
justifyContent: 'center'
},
container2: {
flex: 1,
backgroundColor: '#F7F7F7',
marginTop:60
},
title: {
fontSize: 14,
backgroundColor: '#FFF',
marginTop: 10
},
listItem:{
margin:10,
padding:10,
backgroundColor:"#FFF",
width:"80%",
flex:1,
alignSelf:"center",
flexDirection:"row",
borderRadius:2
},
});
// geht nicht umzubennen nochmal gucken
const styles = StyleSheet.create({
item: {
backgroundColor: '#f9c2ff',
padding: 20,
marginVertical: 8,
marginHorizontal: 16,
},
container:{
flex: 1,
marginTop: 20,
},
group: {
flexDirection: 'row',
justifyContent: 'space-around',
},
SeparatorLine :{
backgroundColor : '#fff',
width: 1,
height: 40
},
elementsContainer: {
backgroundColor: '#ecf5fd',
}
});
export default class Willkommen extends Component {
render() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Auswahl"
component={Auswahl}
/>
<Stack.Screen
name="UebungenAnzeigen"
component={UebungenAnzeigen}
/>
</Stack.Navigator>
</NavigationContainer>
);
}
}
registerRootComponent(Willkommen);
I don't completely understand the question. Because its just if else to check which one is selected (according to your schema).
How you will pass values from one screen to another is as follows.
<Button style={{margin:10, padding:10}} title="Erstelle meinen Plan" onPress={() =>
this.props.navigation.navigate('UebungenAnzeigen',{
data : {value1, value2 ,...etc}}) }/>
And on next screen you can receive that data using following code.
let data = props.route.params?.data;
console.log(data.value1, data.value2)

Fetch data from realtime database firebase in react native?

I already have data in my realtime database. I can also fetch it successfully. Now what I need to do is output it in a tinder-like card view. I am currently outputting data using a 'Demo' file which exports a hard-coded array that contains sample information of some users. Using the demo array, the card output is working. But when I fetch data from firebase and store it in an array named items[], nothing is displayed on my output screen. My code is as follows:
Home Screen
import React from 'react';
import { View, ImageBackground } from 'react-native';
import CardStack, { Card } from 'react-native-card-stack-swiper';
import City from '../components/City';
import Filters from '../components/Filters';
import CardItem from '../components/CardItem';
import styles from '../assets/styles';
import Demo from '../assets/demo';;
import {db} from '../config/config';
class Home extends React.Component {
constructor (props) {
super(props);
this.state = ({
items: []
});
}
componentWillMount() {
var items = [];
db.ref('cards').once('value', (snap) => {
snap.forEach((child) => {
let item = child.val();
item.id = child.key;
items.push({
pet_name: child.val().pet_name,
pet_gender: child.val().pet_gender,
pet_age: child.val().pet_age,
pet_breed: child.val().pet_breed,
photoUrl: child.val().photoUrl,
});
});
//console.log(items)
this.setState({ items: items });
console.log(items);
});
}
render() {
return (
<ImageBackground
source={require('../assets/images/bg.png')}
style={styles.bg}
>
<View style={styles.containerHome}>
<View style={styles.top}>
<City />
<Filters />
</View>
<CardStack
loop={true}
verticalSwipe={false}
renderNoMoreCards={() => null}
ref={swiper => {
this.swiper = swiper
}}
>
{Demo.map((item, index) => (
<Card key={index}>
<CardItem
image={item.image}
name={item.name}
description={item.description}
actions
onPressLeft={() => this.swiper.swipeLeft()}
onPressRight={() => this.swiper.swipeRight()}
/>
</Card>
))}
</CardStack>
</View>
</ImageBackground>
)
}
}
export default Home;
Demo Data
module.exports = [
{
id: 3,
name: 'whatever',
status: 'Online',
match: '78',
description:
'Full-time Traveller. Globe Trotter. Occasional Photographer. Part time Singer/Dancer.',
message:
'I will go back to Gotham and I will fight men Iike this but I will not become an executioner.',
image: require('./images/01.jpg')
},
{
id: 2,
name: 'Clementine Bauch',
match: '93',
description:
'Full-time Traveller. Globe Trotter. Occasional Photographer. Part time Singer/Dancer.',
status: 'Offline',
message: "Someone like you. Someone who'll rattle the cages.",
image: require('./images/02.jpg')
}
];
fetching data:
import {db} from '../config/config';
var items = [];
db.ref('cards').once('value', (snap) => {
snap.forEach((child) => {
let item = child.val();
item.id = child.key;
items.push({
pet_name: child.val().pet_name,
pet_gender: child.val().pet_gender,
pet_age: child.val().pet_age,
pet_breed: child.val().pet_breed,
photoUrl: child.val().photoUrl,
});
});
//console.log(items)
for (var i in items){
console.log(items[i])
}
});
export var items;
I want to use my items[] array instead of the Demo hard-coded array. How do I do this?
The output of items[] array:
Array [
Object {
"pet_age": "11",
"pet_breed": "golden retriever",
"pet_gender": "male",
"pet_name": "dawn",
"photoUrl": "picture",
},
Object {
"pet_age": "7",
"pet_breed": "German",
"pet_gender": "Male",
"pet_name": "Rambo",
"photoUrl": "https://firebasestorage.googleapis.com/v0/b/woofmatix-50f11.appspot.com/o/pFkdnwKltNVAhC6IQMeSapN0dOp2?alt=media&token=36087dae-f50d-4f1d-9bf6-572fdaac8481",
},
]
CardItem component:
import React from 'react';
import styles from '../assets/styles';
import { Text, View, Image, Dimensions, TouchableOpacity } from 'react-native';
import Icon from './Icon';
const CardItem = ({
actions,
description,
image,
matches,
name,
pet_name,
pet_gender,
pet_age,
onPressLeft,
onPressRight,
status,
variant
}) => {
// Custom styling
const fullWidth = Dimensions.get('window').width;
const imageStyle = [
{
borderRadius: 8,
width: variant ? fullWidth / 2 - 30 : fullWidth - 80,
height: variant ? 170 : 350,
margin: variant ? 0 : 20
}
];
const nameStyle = [
{
paddingTop: variant ? 10 : 15,
paddingBottom: variant ? 5 : 7,
color: '#363636',
fontSize: variant ? 15 : 30
}
];
return (
<View style={styles.containerCardItem}>
{/* IMAGE */}
<Image source={image} style={imageStyle} />
{/* MATCHES */}
{matches && (
<View style={styles.matchesCardItem}>
<Text style={styles.matchesTextCardItem}>
<Icon name="heart" /> {matches}% Match!
</Text>
</View>
)}
{/* NAME */}
<Text style={nameStyle}>{name}</Text>
{/* DESCRIPTION */}
{description && (
<Text style={styles.descriptionCardItem}>{description}</Text>
)}
{/* STATUS */}
{status && (
<View style={styles.status}>
<View style={status === 'Online' ? styles.online : styles.offline} />
<Text style={styles.statusText}>{pet_age}</Text>
</View>
)}
{/* ACTIONS */}
{actions && (
<View style={styles.actionsCardItem}>
<View style={styles.buttonContainer}>
<TouchableOpacity style={[styles.button, styles.red]} onPress={() => {
this.swiper.swipeLeft();
}}>
<Image source={require('../assets/red.png')} resizeMode={'contain'} style={{ height: 62, width: 62 }} />
</TouchableOpacity>
<TouchableOpacity style={[styles.button, styles.orange]} onPress={() => {
this.swiper.goBackFromLeft();
}}>
<Image source={require('../assets/back.png')} resizeMode={'contain'} style={{ height: 32, width: 32, borderRadius: 5 }} />
</TouchableOpacity>
<TouchableOpacity style={[styles.button, styles.green]} onPress={() => {
this.swiper.swipeRight();
}}>
<Image source={require('../assets/green.png')} resizeMode={'contain'} style={{ height: 62, width: 62 }} />
</TouchableOpacity>
</View>
</View>
)}
</View>
);
};
export default CardItem;

Fetch data from firebase realtime database, React Native (expo)

I have that code, I need to fetch data instead of the static array here.
Note: have connected to firebase realtime database and all that stuff, I just need to fetch data and map them, I will need to render them in a list.
const rec = [
{
name: 'Brothers Restaurant',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/ladylexy/128.jpg',
address: 'Address St. Random Number',
link: 'Home'
},
{
name: 'Example Restaurant',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg',
address: 'Address St. Random Number 23',
link: 'About'
},
{
name: 'Example Restaurant',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg',
address: 'Address St. Random Number 23',
link: 'About'
},
{
name: 'Example Restaurant',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg',
address: 'Address St. Random Number 23',
link: 'About'
},
]
const discover = [
{
name: 'Discover Restaurant',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/ladylexy/128.jpg',
address: 'Address St. Random Number',
link: 'Home'
},
{
name: 'Example Discover Restaurant',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg',
address: 'Address St. Random Number 23',
link: 'About'
},
{
name: 'Discover Restaurant',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/ladylexy/128.jpg',
address: 'Address St. Random Number',
link: 'Home'
},
{
name: 'Example Discover Restaurant',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg',
address: 'Address St. Random Number 23',
link: 'About'
},
{
name: 'Discover Restaurant',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/ladylexy/128.jpg',
address: 'Address St. Random Number',
link: 'Home'
},
{
name: 'Example Discover Restaurant',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg',
address: 'Address St. Random Number 23',
link: 'About'
},
]
export default class RestaurantScreen extends Component {
static navigationOptions = {
title: 'Restaurants',
headerStyle: {
backgroundColor: '#c4463d',
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
},
}
render() {
return (
<View style={styles.container}>
<Text style={{ fontSize: 24, fontWeight: '700', color: '#c4463d' }}>Recommendations</Text>
<ScrollView
style={styles.categories}>
<View>
{
rec.map((l, i) => (
<ListItem
key={i}
leftAvatar={{ source: { uri: l.avatar_url } }}
title={l.name}
address={l.subtitle}
onPress={() => this.props.navigation.navigate(`${l.link}`)}
bottomDivider
/>
))
}
</View>
</ScrollView>
<View style={styles.recommendations}>
<Text style={{ fontSize: 24, fontWeight: '700', color: '#c4463d' }}>Discover</Text>
<ScrollView>
{
discover.map((l, i) => (
<ListItem
key={i}
leftAvatar={{ source: { uri: l.avatar_url } }}
title={l.name}
address={l.subtitle}
bottomDivider
/>
))
}
</ScrollView>
</View>
</View>
)
}
}
official documentation from expo didn't help a lot to be honest ^^ and I can't get this thing posted because I have a lot of code in here? -.-
Basically if everything is set up, you just need to put listener at lifecycle method (componentDidMount) and set the data inside state.
for more info, you can check firebase js sdk
https://firebase.google.com/docs/web/setup
export default class RestaurantScreen extends Component {
state = {
rec: [],
discover: []
}
static navigationOptions = {
title: 'Restaurants',
headerStyle: {
backgroundColor: '#c4463d',
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
},
}
componentDidMount() {
firebase.database().ref('places').on('value', (snapshot) => {
const rec = snapshot.val();
this.setState({ rec, discover: rec })
});
}
render() {
const { rec, discover } = this.state;
return (
<View style={styles.container}>
<Text style={{ fontSize: 24, fontWeight: '700', color: '#c4463d' }}>Recommendations</Text>
<ScrollView
style={styles.categories}>
<View>
{
rec.map((l, i) => (
<ListItem
key={i}
leftAvatar={{ source: { uri: l.avatar_url } }}
title={l.name}
address={l.subtitle}
onPress={() => this.props.navigation.navigate(`${l.link}`)}
bottomDivider
/>
))
}
</View>
</ScrollView>
<View style={styles.recommendations}>
<Text style={{ fontSize: 24, fontWeight: '700', color: '#c4463d' }}>Discover</Text>
<ScrollView>
{
discover.map((l, i) => (
<ListItem
key={i}
leftAvatar={{ source: { uri: l.avatar_url } }}
title={l.name}
address={l.subtitle}
bottomDivider
/>
))
}
</ScrollView>
</View>
</View>
)
}
}

Can't pass value as function in React Navite Element Button

I want to display model with the key value from array, but I can't do it, and I don't understand the problem.
this is react native in Expo and I have used react native elements
import React, {Component} from "react";
import { ScrollView, Text, Linking, View, Modal } from "react-native";
import { Card, Button } from "react-native-elements";
import PriceDetail from "./PriceDetail";
const images = [
{
key: 1,
name: "Nathan Anderson",
image: require("../images/1.jpg"),
url: "https://unsplash.com/photos/C9t94JC4_L8"
},
{
key: 2,
name: "Jamison McAndie",
image: require("../images/2.jpg"),
url: "https://unsplash.com/photos/waZEHLRP98s"
},
{
key: 3,
name: "Alberto Restifo",
image: require("../images/3.jpg"),
url: "https://unsplash.com/photos/cFplR9ZGnAk"
},
{
key: 4,
name: "John Towner",
image: require("../images/4.jpg"),
url: "https://unsplash.com/photos/89PFnHKg8HE"
}
];
class Home extends Component {
state = {
selectedItem : null,
mvisible : false
}
modalClosedHandler = () => {
this.setState({
mvisible: false,
selectedItem: null
});
};
productSelectedHandler = key => {
this.setState(prevState => {
return {
selectedItem: prevState.images.find(image => {
return image.key === key;
})
};
});
console.log(selectedItem);
};
showModal = (key) => {
this.setState({
mvisible: true,
selectedItem: key
});
}
render () {
return (
<View style={{ flex: 1 }}>
<Modal
visible={this.state.mvisible}
onRequestClose={this.modalClosedHandler}>
<View style={{flex : 1, alignItems: 'center', justifyContent: 'center'}}>
<Text>Hello this is modal{this.state.selectedItem}</Text>
<Button title="Close" onPress={this.modalClosedHandler}/>
</View>
</Modal>
<ScrollView contentContainerStyle={{ paddingVertical: 20 }}>
{images.map(({ name, image, url, key }) => (
<Card title={`Product ${key}`} image={image} key={key}>
<Text style={{ marginBottom: 10 }}>
Photo by {name}.
</Text>
<Button
backgroundColor="#03A9F4"
title="VIEW NOW"
onPress={(key)=>this.showModal(key)}
/>
</Card>
))}
</ScrollView>
</View>
);
}
}
export default Home;
I am new to react native.
You wont get key in the first parameter of button's onPress.
This is wrong:
<Button
backgroundColor="#03A9F4"
title="VIEW NOW"
onPress={(key)=>this.showModal(key)}
/>
You already have a key at higher level, so you should use this code:
<Button
backgroundColor="#03A9F4"
title="VIEW NOW"
onPress={()=>this.showModal(key)}
/>
I'm not sure to understand well but if you have a problem while calling this.showModal is because you have an extra "key".
Replace
<Button
backgroundColor="#03A9F4"
title="VIEW NOW"
onPress={(key)=>this.showModal(key)}
/>
By
<Button
backgroundColor="#03A9F4"
title="VIEW NOW"
onPress={()=>this.showModal(key)}
/>

What Approach should I use to make each cards swipe either right/left as tinder?React Native?

What approach should I use to make each cards swipe either right/left as tinder?
My cards are in listview.Once I swipe any card right or left it should vanish off and the next stacked card should come up at that place? In React Native.
The imports :
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View,Image,ListView,TouchableOpacity
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import { TabNavigator, StackNavigator } from 'react-navigation';
import { Col, Row, Grid } from 'react-native-easy-grid';
import { Container, Header, Content, Card, CardItem, Thumbnail, Button, Left, Body, Right } from 'native-base';
const instructions = Platform.select({
ios: 'Press Cmd+R to reload,\n' +
'Cmd+D or shake for dev menu',
android: 'Double tap R on your keyboard to reload,\n' +
'Shake or press menu button for dev menu',
});
export default class Scenes extends Component{
static navigationOptions = {
tabBarLabel: 'Scenes',
tabBarIcon: ({ tintColor }) => (
<Image
source={require('./video.png')}
style={[styles.icon, {tintColor: tintColor}]}
/>
),
};
Function displaying users:
displayImages(users){
var {navigate} = this.props.navigation;
return(
<View style={styles.container}>
<Content style={{paddingTop: 20, borderWidth: 0, shadowOpacity: 0,
shadowOffset: {
height: 0,
width:0
},
shadowRadius: 0,}}>
<Card style={{borderWidth: 0}} transparent>
<CardItem style={{height: 48,borderWidth:0,}}>
<Left>
<Thumbnail source={{uri: users.avatar_url}} style={{height: 40, width: 40}} />
<Body>
<Text style={styles.uploaderName}>{users.name}</Text>
</Body>
</Left>
<Right>
<Image
source={require('./follow.png')}
style={{height: 23, width: 42}}
/>
</Right>
</CardItem>
<CardItem cardBody>
<Image source={{uri: users.image}} style={{height: 322, width: null, flex: 1}}/>
</CardItem>
<CardItem style={{height: 48,borderWidth:0,}}>
<Left>
<TouchableOpacity onPress = { () => navigate ("profile", {}) }>
<Icon style={{color:'#f00039'}} name={'md-heart'} size={20}/>
</TouchableOpacity>
<Text style={{marginLeft:2}}>46</Text>
<Image
source={require('./sharePost.png')}
style={{height: 20, width: 25, marginLeft: 15}}
/>
</Left>
<Body>
<Button transparent>
</Button>
</Body>
<Right>
</Right>
</CardItem>
</Card>
</Content>
</View>
);
}
The render method:
render() {
var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
var users = [
{
name: 'Amy Farha',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/ladylexy/128.jpg',
image: 'https://i.pinimg.com/564x/1c/f3/05/1cf305362aed02ad559f989687b1460e.jpg',
},
{
name: 'Chris Jackson',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg',
image: 'https://i.pinimg.com/236x/a8/37/8e/a8378eeb01ec788a0068ea6b1b759091.jpg',
},
{
name: 'Amanda Martin',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/brynn/128.jpg',
image: 'https://i.pinimg.com/564x/8a/db/a7/8adba7207bdc82668bf06acc2734537e.jpg',
},
{
name: 'Amy Farha',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/ladylexy/128.jpg',
image: 'https://i.pinimg.com/564x/8a/db/a7/8adba7207bdc82668bf06acc2734537e.jpg',
},
{
name: 'Chris Jackson',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg',
image: 'https://i.pinimg.com/564x/66/f0/2f/66f02f37eb54ff7f79f4c831212b231f.jpg',
},
{
name: 'Amanda Martin',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/brynn/128.jpg',
image: 'https://i.pinimg.com/564x/58/0c/78/580c789ded6ceeafdf71b792b0d57ac6.jpg',
},
{
name: 'Amy Farha',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/ladylexy/128.jpg',
image: 'https://i.pinimg.com/564x/a5/4d/4d/a54d4d37522a76a67002fa25b8e51515.jpg',
},
{
name: 'Chris Jackson',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg',
image: 'https://i.pinimg.com/564x/47/6b/5c/476b5c4c9725ff3cd4bb3e5f61e4d6c3.jpg',
},
{
name: 'Amanda Martin',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/brynn/128.jpg',
image: 'https://i.pinimg.com/564x/ad/4b/06/ad4b06523eefacc30d09d41a9992029f.jpg',
},
{
name: 'Christy Thomas',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/kfriedson/128.jpg',
image: 'https://i.pinimg.com/564x/a5/4d/4d/a54d4d37522a76a67002fa25b8e51515.jpg',
},
{
name: 'Melissa Jones',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/nuraika/128.jpg',
image: 'https://i.pinimg.com/564x/82/ac/2e/82ac2e1c86692090173666496b9ce1cf.jpg',
},
{
name: 'Amanda Martin',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/brynn/128.jpg',
image: 'https://i.pinimg.com/564x/8a/db/a7/8adba7207bdc82668bf06acc2734537e.jpg',
},
{
name: 'Christy Thomas',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/kfriedson/128.jpg',
image: 'https://i.pinimg.com/564x/a5/4d/4d/a54d4d37522a76a67002fa25b8e51515.jpg',
},
{
name: 'Melissa Jones',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/nuraika/128.jpg',
image: 'https://i.pinimg.com/564x/ae/b6/ac/aeb6ac2f05644f1464c298bf979630e9.jpg',
},
{
name: 'Christy Thomas',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/kfriedson/128.jpg',
image: 'https://i.pinimg.com/564x/57/ac/3e/57ac3e724c61f9b9803d520574e42a1e.jpg',
},
{
name: 'Melissa Jones',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/nuraika/128.jpg',
image: 'https://i.pinimg.com/564x/66/f0/2f/66f02f37eb54ff7f79f4c831212b231f.jpg',
},
];
The view component:
var cloneUsers = ds.cloneWithRows(users);
return (
<View style={{flex: 1}}>
<ListView
style={styles.listView}
dataSource={cloneUsers}
renderRow={this.displayImages.bind(this)}
renderSeparator={(sectionId, rowId) => <View key={rowId} style={styles.separator} />}
/>
</View>
);
}
}
This is the styling:
const styles = StyleSheet.create({
icon: {
width: 26,
height: 26,
},
container: {
flex: 1,
backgroundColor: '#F5F5F5',
paddingHorizontal : 25,
},
uploaderName:{
fontSize: 16,
color: '#36292a'
}
});
In React I used HammerJS to do this.
ReactNative has a built in library called PanResponder. There are examples out there.
To make a swipe deck like Tinder in react-native you can use a library called react-native-swipe-decker. It's a pretty straightforward library, there's a stack of cards and there are actions like onSwipedLeft onSwipedRight onSwipedAll. You can define functions for each of them if you wish to customize. By default all the card contents need to be in an array and no matter which direction you swipe you move to the next card. You can also add infinite loop to it. You can have a look at the GitHub repository for the project and check out their example.

Resources