Attempt to import and use NUMBERPLEASE in React Native Successfully - reactjs

Below you can find the code created so far. You might see that this code works for a simple web program. But when you attempt to see how it is displayed on MOBILE this error code occurs -> (undefined is not an object (evaluating 'p.Picker.Item')
(Device))
Would anyone possibly have an idea of the reason for this error?
I'm new to REACT NATIVE.
import React, { useState } from 'react';
import {
View,
StyleSheet,
Text,
Animated,
Easing,
Pressable,
TextInput,
} from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';
import Constants from 'expo-constants';
import {Card} from 'react-native-paper';
import NumberPlease from 'react-native-number-please';
import { useHeaderHeight } from '#react-navigation/elements';
const OrderPizza = () => {
const initialValues = [{ id: "pizza", value: 3 }];
const [pizzas, setPizzas] = useState(initialValues);
const pizzaNumbers = [{ id: "pizza", label: "🍕", min: 0, max: 99 }];
return (
<View>
<Text>I would like</Text>
<NumberPlease
digits={pizzaNumbers}
values={pizzas}
onChange={(values) => setPizzas(values)}
/>
</View>
);
};
export default function DosingCalculator({ navigation }) {
const headerHeight = useHeaderHeight();
const topMargin = headerHeight + 'px 0 0 0';
const animatedValue = React.useRef(new Animated.Value(0)).current;
const startAnimation = (toValue) => {
Animated.timing(animatedValue, {
toValue,
duration: 400,
easing: Easing.linear,
useNativeDriver: false,
}).start();
};
const left = animatedValue.interpolate({
inputRange: [0, 1],
outputRange: ['2%', '50%'],
extrapolate: 'clamp',
});
const scale = animatedValue.interpolate({
inputRange: [0, 0.5, 1],
outputRange: [1, 0.9, 1],
extrapolate: 'clamp',
});
return (
<LinearGradient colors={['#20c1c1', '#8dc642']} style={styles.gradient}>
<View style={styles.mainContainer}>
<View style={styles.container}>
<Text>
Secondary Readings
<View style={styles.sliderContainer}>
<Animated.View style={[styles.slider, { left }]} />
<Pressable
style={styles.clickableArea}
onPress={startAnimation.bind(null, 0)}>
<Animated.Text
style={[styles.sliderText, { transform: [{ scale }] }]}>
Show
</Animated.Text>
</Pressable>
<Pressable
style={styles.clickableArea}
onPress={startAnimation.bind(null, 1)}>
<Animated.Text
style={[styles.sliderText, { transform: [{ scale }] }]}>
Hide
</Animated.Text>
</Pressable>
</View>
</Text>
<View
style={{
flex: 1,
alignContent: 'center',
justifyContent: 'center',
padding: 12,
}}>
<Text>Pool Volume</Text>
<TextInput
style={{
borderRadius: 10,
padding: 8,
backgroundColor: '#f5f5f5',
}}
onChangeText={(text) => setGallons(text)}
/>
</View>
</View>
<View style={styles.container}>
<Text>Current</Text>
<OrderPizza/>
</View>
<View style={styles.container}>
<Text>Desired</Text>
</View>
</View>
</LinearGradient>
);
}
const styles = StyleSheet.create({
container: {
width: '100%',
alignItems: 'center',
justifyContent: 'center',
textAlign: 'center',
margin: 30,
flexDirection: 'row',
},
gradient: {
flex: 1,
paddingLeft: 15,
paddingRight: 15,
},
sliderContainer: {
width: '75%',
height: 50,
borderRadius: 10,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
backgroundColor: '#e0e0e0',
},
mainContainer: {
width: '100%',
margin: 8,
borderRadius: 10,
alignItems: 'center',
backgroundColor: 'white',
},
clickableArea: {
width: '50%',
height: '100%',
justifyContent: 'center',
alignItems: 'center',
},
sliderText: {
fontSize: 17,
fontWeight: '500',
},
slider: {
position: 'absolute',
width: '48%',
height: '90%',
borderRadius: 10,
backgroundColor: '#20c1c1',
},
});

Related

have Request failed with status code 400 error in react native

I am using Axios to get data from JSON files and I tried it in postman it works, also the app works but sometimes when I open the app this error appears: Request failed with status code 400 and data disappears can you help solve. am I fetching data in the wrong way?
if there another way to avoid this error please mention it
here is my code:
`
import { StyleSheet, Text, View, Image, ScrollView, TouchableOpacity, TextInput, Pressable, Dimensions } from 'react-native'
import React, { useEffect, useState } from 'react'
import { useNavigation, useRoute } from "#react-navigation/native";
import axios from 'axios';
import LottieView from 'lottie-react-native';
import { Rating } from 'react-native-stock-star-rating'
import { AntDesign } from '#expo/vector-icons';
const LoadingDirection = () => {
return (
<LottieView
ref={animation => {
animation = animation
}}
style={{
width: 210,
height: 210,
alignSelf: 'center'
}}
source={require('../../assets/gif/loading.json')}
autoPlay
loop
/>
)
}
const ArtistSearch = () => {
const route = useRoute()
let token = route.params.token
const navigation = useNavigation();
const [artist, setArtist] = useState([]);
const [loaded, setLoaded] = useState(false);
const [search, setSearch] = useState('');
const [masterData, setMasterData] = useState([]);
const [empty, SetEmpty] = useState(false)
const ArtistData = async () => {
const resp = await axios.get('https://api.spotify.com/v1/search?query=remaster%2520track%3ADoxy%2520artist%3AMiles%2520Davis&type=artist&market=ES&locale=en-US%2Cen%3Bq%3D0.9&offset=5&limit=10', {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: "Bearer " + token,
},
})
return resp.data.artists.items;
};
useEffect(() => {
ArtistData().then(artists => {
setArtist(artists)
setMasterData(artists)
setLoaded(true);
}).catch(err => {
console.log(err)
});
}, []);
return (
<ScrollView>
<View style={{ alignItems: 'center', marginTop: 20 }}>
<Pressable>
<View style={styles.searchSection}>
<TextInput
style={styles.input}
placeholder="Search for an artist..."
underlineColorAndroid="transparent"
value={search}
/>
<AntDesign name="search1" size={24} color="Black" />
</View>
</Pressable>
</View>
{artist.map((data, i) => (
<TouchableOpacity onPress={() => { navigation.navigate('AlbumScreen',{artistId:data.id,token:token,artistName:data.name}) }} key={i}>
<View>
<View style={styles.paper}>
<Image source={{ uri: data.images.url }} style={{ height: 350, width: Dimensions.get('window').width - 40, resizeMode: 'cover' }} />
<View style={{ height: 1, width: Dimensions.get('window').width - 40, backgroundColor: 'gray', marginBottom: 10 }}></View>
<Text style={{ paddingLeft: 10, fontSize: 24, fontWeight: '600' }}>{data.name}</Text>
<Text style={{ color: 'gray', marginLeft: 10, marginBottom: 10 }}>{data.followers.total} followers</Text>
<View style={{ marginLeft: 10 }}>
<Rating stars={data.popularity / 2} maxStars={5} size={25} />
</View>
<View style={{ marginBottom: 20 }} />
</View>
</View>
</TouchableOpacity>
))}
{!loaded && LoadingDirection()}
</ScrollView>
)
}
export default ArtistSearch
const styles = StyleSheet.create({
paper: {
width: Dimensions.get('window').width - 40,
backgroundColor: 'white',
shadowColor: 'black',
shadowOffset: {
width: 0,
height: 4,
},
shadowOpacity: 0.002,
shadowRadius: 22,
elevation: 3,
margin: 8,
marginTop: 20,
marginLeft: 20,
marginRight: 20,
borderColor: 'gray',
borderWidth: 0.2
},
heading: {
fontSize: 17,
marginBottom: 5,
marginLeft: 10,
marginTop: 10
},
stars: {
display: 'flex',
flexDirection: 'row',
marginLeft: 10, marginBottom: 20
},
starUnselected: {
color: '#aaa',
},
starSelected: {
color: '#ffb300',
},
searchSection: {
width: Dimensions.get('window').width - 40,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
borderColor: 'Black',
borderWidth: 1,
borderRadius: 10,
paddingHorizontal: 10
},
searchIcon: {
padding: 10,
},
input: {
flex: 1,
paddingTop: 10,
paddingRight: 10,
paddingBottom: 10
},
})
`

Centering content in the middle of the screen in a react native application

i want to center my view at the center of the screen but its unable am using justifyContent: 'center',
alignItems: 'center', but its all unable to put the contents at the middle of the screen i want the content to go to middle of the screen
i want the buttons and the inputs all to be at the middle of the screen .
i have tried to align but its unable to
import React, {useState, useEffect, useContext} from 'react';
import UserContext from './useContextStore';
import {
Text,
View,
Button,
TextInput,
StyleSheet,
TouchableOpacity,
Platform,
} from 'react-native';
import AsyncStorage from '#react-native-async-storage/async-storage';
import auth from '#react-native-firebase/auth';
import DataViewDoc from './view';
const PhoneInput = ({navigation}) => {
const [number, setNumber] = useState({number: ''});
const [value, loadedVal] = useState({value: true});
const [screenDaetail, setScreenDaetail] = useState(true);
const [waiting, setwaiting] = useState(false);
const [code, setCode] = useState({code: '', number: ''});
const [confirm, setConfirm] = useState(null);
const [codee, setCodee] = useState('');
// let num;
const getNumber = (val) => {
setNumber({number: val});
};
const getCode = (val) => {
setCode({code: val, number: number.number});
};
//firebase**************************************************************************
async function signInWithPhoneNumber(phoneNumber) {
const confirmation = await auth().signInWithPhoneNumber(phoneNumber);
console.log('confirmation code is ', confirmation);
setConfirm(confirmation);
}
async function confirmCode() {
try {
await confirm.confirm(codee).then(() => {
console.log('logged in');
// setScreenDaetail(!screenDaetail);
navigation.navigate('codeForma');
});
} catch (error) {
console.log('Invalid code.');
}
}
return (
<View styles={style.container}>
{confirm ? (
<>
<View styles={style.content}>
<Text style={style.TextStyle1}>Enter Valid Code </Text>
</View>
<View style={style.viewForText}>
<TextInput
style={style.textinput}
onChangeText={(text) => setCodee(text)}
secureTextEntry={true}
maxLength={13}
value={codee}
/>
</View>
<View style={style.viewForSend}>
<TouchableOpacity
style={style.SubmitButtonStyle}
activeOpacity={0.1}
onPress={() => {
// sendPhoneCodeTwillio();
confirmCode();
}}>
<Text style={style.TextStyle}> SEND</Text>
</TouchableOpacity>
<TouchableOpacity
style={style.SubmitButtonStyle2}
activeOpacity={0.1}
onPress={() => {
// sendPhoneTwilio();
setConfirm(null);
}}>
<Text style={style.TextStyle}> Back </Text>
</TouchableOpacity>
</View>
</>
) : (
<>
<View styles={style.content}>
<Text style={style.TextStyle1}>Enter Phone number </Text>
</View>
<View style={style.viewForText}>
<TextInput
style={style.textinput}
onChangeText={(text) => {
getNumber(text);
}}
maxLength={13}
value={number.number}
/>
</View>
<View style={style.viewForSend}>
<TouchableOpacity
style={style.SubmitButtonStyle}
activeOpacity={0.1}
onPress={() => {
signInWithPhoneNumber(number.number);
}}>
<Text style={style.TextStyle}> SEND </Text>
</TouchableOpacity>
<TouchableOpacity
style={style.SubmitButtonStyle2}
activeOpacity={0.1}
onPress={() => {
signInWithPhoneNumber(number.number);
}}>
<Text style={style.TextStyle}> RESEND </Text>
</TouchableOpacity>
</View>
</>
)}
</View>
);
};
const style = StyleSheet.create({
container: {
flex: 1,
// paddingBottom: Platform.OS === 'android' ? 50 : 0,
justifyContent: 'center',
alignItems: 'center',
},
textinput: {
margin: 25,
borderColor: '#7a42f4',
borderWidth: 5,
borderRadius: 35,
color: 'black',
textAlign: 'center',
fontFamily: 'Cochin',
fontSize: 20,
fontWeight: 'bold',
},
viewForText: {width: 250, alignSelf: 'center'},
viewForSend: {
width: 400,
// alignSelf: 'baseline',
borderRadius: 20,
margin: 10,
flexDirection: 'row',
justifyContent: 'center',
alignSelf: 'center',
},
content: {
// justifyContent: 'center',
// // alignItems: 'flex-start',
flex: 2,
justifyContent: 'flex-end',
marginBottom: 36,
},
topTierblack: {
backgroundColor: 'black',
borderRadius: 100,
width: 300,
marginLeft: 40,
opacity: 0.5,
},
topTierRed: {
backgroundColor: 'red',
borderRadius: 100,
width: 300,
marginLeft: 40,
},
topTierGreen: {
backgroundColor: 'green',
borderRadius: 100,
width: 300,
marginLeft: 40,
opacity: 0.5,
},
viewForSend2: {
width: 200,
alignSelf: 'flex-end',
borderRadius: 20,
// margin: 10,
},
buttonContainer: {
width: '40%',
alignSelf: 'center',
marginVertical: 30,
color: 'red',
borderRadius: 10,
},
SubmitButtonStyle: {
marginTop: 10,
paddingTop: 15,
paddingBottom: 15,
marginLeft: 30,
marginRight: 30,
backgroundColor: '#00BCD4',
borderRadius: 10,
borderWidth: 1,
borderColor: '#fff',
shadowOpacity: 0.5,
shadowColor: 'blue',
height: 50,
width: 100,
},
SubmitButtonStyle2: {
marginTop: 10,
paddingTop: 15,
paddingBottom: 15,
marginLeft: 30,
marginRight: 30,
backgroundColor: 'black',
borderRadius: 10,
borderWidth: 1,
borderColor: '#fff',
shadowOpacity: 0.5,
shadowColor: 'blue',
height: 50,
width: 100,
},
TextStyle: {
color: '#fff',
textAlign: 'center',
},
TextStyle1: {
color: 'black',
textAlign: 'center',
fontFamily: 'Cochin',
fontSize: 20,
fontWeight: 'bold',
},
});
export default PhoneInput;
Remove the marginRight from SubmitButtonStyle and the marginLeft from SubmitButtonStyle2 and you should be fine.

How to move down a object using button in react native?

Actually I want to do something like that (Image attached):
There have a box, and two buttons. If I press button 1 then the box moved left. And if I press button 2 then the box moved right.
I want, when the box move right and overcome the bar 1 then the box moved down on the bar 2.
But I have no idea how to do it.
Here is my code:
import React, {Component} from 'react';
import {
View,
Text,
StyleSheet,
Animated,
TouchableOpacity,
ScrollView,
Image,
} from 'react-native';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
left: 20,
};
}
moveRight = () => {
this.setState({left: this.state.left + 10}); // 10 is value of change.
};
moveLeft = () => {
this.setState({left: this.state.left - 10}); // 10 is value of change.
};
render() {
return (
<View style={styles.container}>
<Image
style={{left: this.state.left, height: 120, width: 120}}
source={require('./assets/box.png')}
/>
<Image
style={{height: 20, width: 180, marginTop: -12, marginLeft: 25}}
source={require('./assets/log.png')}
/>
<Image
style={{height: 20, width: 200, marginTop: 150, marginLeft: 185}}
source={require('./assets/log.png')}
/>
<View style={styles.buttonsContainer}>
<TouchableOpacity onPress={this.moveLeft}>
<Image
style={{height: 60, width: 60}}
source={require('./assets/left-button.png')}
/>
</TouchableOpacity>
<TouchableOpacity onPress={this.moveRight}>
<Image
style={{height: 60, width: 60}}
source={require('./assets/right-button.png')}
/>
</TouchableOpacity>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
textCenter: {
alignSelf: 'center',
textAlign: 'center',
},
levelHeading: {
fontWeight: 'bold',
fontSize: 35,
color: '#CC8A4F',
},
buttonsContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
marginTop: 200,
paddingLeft: 80,
paddingRight: 80,
},
});
Please help me!
Thanks!
import React, { useEffect } from "react";
import { Animated, Text, View, StyleSheet, Button } from "react-native";
const App = () => {
const moveAnimation = new Animated.ValueXY({ x: 10, y: 450 });
useEffect(() => {
moveAnimation;
}, []);
const _moveBallLeft = () => {
Animated.spring(moveAnimation, {
toValue: { x: 250, y: 450 },
}).start();
};
const _moveBallRight = () => {
Animated.spring(moveAnimation, {
toValue: { x: 10, y: 450 },
}).start();
};
return (
<View style={styles.container}>
<Animated.View style={[styles.tennisBall, moveAnimation.getLayout()]}>
<View style={styles.button}>
<Text style={styles.buttonText}>ball</Text>
</View>
</Animated.View>
<View
style={{
flexDirection: "row-reverse",
justifyContent: "space-evenly",
}}
>
<View style={{ alignSelf: "center" }}>
<Button title=">" onPress={_moveBallLeft}></Button>
</View>
<View style={{ alignSelf: "center", marginLeft: "2%" }}>
<Button title="<" onPress={_moveBallRight}></Button>
</View>
</View>
</View>
);
};
export default App;
const styles = StyleSheet.create({
container: {
flex: 2,
backgroundColor: "#ecf0f1",
},
tennisBall: {
display: "flex",
justifyContent: "center",
alignItems: "center",
backgroundColor: "greenyellow",
borderRadius: 100,
width: 100,
height: 100,
},
button: {
paddingTop: 24,
paddingBottom: 24,
},
buttonText: {
fontSize: 24,
color: "#333",
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

how to detect a face with react-native-camera facedetector?

I am trying to detect face with react-native-camera, I want to know how can we detect an individual's face, there is no proper documentation about the mlkit.
await FaceDetector.detectFacesAsync(data.uri) this statement is just returning face object like this face[0] = { bounds: { origin: { x: 739, y: 987 }, size: { x: 806, y: 789 } }, faceID: 0, rollAngle: 10.533509254455566, yawAngle: 0.7682874798774719 }.
This is just object's position, I cannot figure out how to recognize individual's face characteristics like eys, nose with the FaceDetector and suppose I will save person A's face data then how I will match the data with A's face later with react-native-camera ?
ML Kit does not support Face Recognition. Also, React Native is not officially supported (yet), but you could check out https://rnfirebase.io/ml-vision/face-detection#process which outlines how you can get a 133-point contour of the face. However, this is not meant for facial recognition, but rather for overlays (e.g. masks, filters).
import SplashScreen from 'react-native-splash-screen'
import React, { useEffect, createRef,useState } from 'react';
import { SafeAreaView, View, Image, StyleSheet, Text, Modal, TouchableOpacity } from 'react-native';
import { RNCamera } from 'react-native-camera';
const Test = (props) => {
useEffect(() => {
SplashScreen.hide();
});
const [faces, setFace] = useState([]);
const [faceavl, setFaceavl] = useState(false);
const [takeTimeFaceAvl, setTakeTimeFaceAvl] = useState(false);
const [searchWaiting, setsearchWaiting] = useState(null)
const [modalVisible, setModalVisible] = useState(false);
const [image, setImage] = useState(null);
const mycamera = createRef()
const PendingView = () => (
<View
style={{
flex: 1,
backgroundColor: 'lightgreen',
justifyContent: 'center',
alignItems: 'center',
}}
>
<Text>Waiting</Text>
</View>
);
const renderFaces = () => (
<View style={{
position: 'absolute',
bottom: 0,
right: 0,
left: 0,
top: 0,
}} pointerEvents="none">
{faces.map(renderFace)}
</View>
);
const renderFace = ({ bounds, faceID, rollAngle, yawAngle }) => (
<View
key={faceID}
transform={[
{ perspective: 600 },
{ rotateZ: `${rollAngle.toFixed(0)}deg` },
{ rotateY: `${yawAngle.toFixed(0)}deg` },
]}
style={[
{
padding: 10,
borderWidth: 1,
borderRadius: 2,
position: 'absolute',
borderColor: '#000',
justifyContent: 'center',
},
{
...bounds.size,
left: bounds.origin.x,
top: bounds.origin.y,
},
]}
>
</View>
);
return (
<>
<SafeAreaView style={styles.container}>
<RNCamera
ref={mycamera}
style={styles.preview}
type={RNCamera.Constants.Type.front}
flashMode={RNCamera.Constants.FlashMode.on}
androidCameraPermissionOptions={{
title: 'Permission to use camera',
message: 'We need your permission to use your camera',
buttonPositive: 'Ok',
buttonNegative: 'Cancel',
}}
androidRecordAudioPermissionOptions={{
title: 'Permission to use audio recording',
message: 'We need your permission to use your audio',
buttonPositive: 'Ok',
buttonNegative: 'Cancel',
}}
onFacesDetected={(data) => {
setFace(data.faces)
setFaceavl(true);
clearTimeout(searchWaiting)
const avc = setTimeout(() => {
console.log()
setFaceavl(false);
setFace([])
}, 500)
setsearchWaiting(avc)
}}
onFaceDetectionError={(error) => {
console.log('face--detact-->', error)
}}
>
{({ camera, status, recordAudioPermissionStatus }) => {
if (status !== 'READY') return <PendingView />;
return (
<View style={{ flex: 0, flexDirection: 'row', justifyContent: 'center' }}>
<TouchableOpacity onPress={async () => {
const options = { quality: 0.5, base64: true };
const data = await camera.takePictureAsync(options)
if (faceavl) {
setTakeTimeFaceAvl(true)
} else {
setTakeTimeFaceAvl(false)
}
console.log(data.uri)
setImage(data)
setModalVisible(!modalVisible)
}} style={styles.capture}>
<Text style={{ fontSize: 14 }}> SNAP </Text>
</TouchableOpacity>
</View>
);
}}
</RNCamera>
{faces ? renderFaces() : null}
</SafeAreaView>
<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
Alert.alert("Modal has been closed.");
setModalVisible(!modalVisible);
}}
>
<View style={styles.centeredView}>
<View style={styles.modalView}>
{takeTimeFaceAvl ? image ? <Image
style={{
width: 200,
height: 100,
}}
source={{
uri: image.uri,
}}
/> : null : <Text>Face not found</Text>}
<TouchableOpacity
style={[styles.button, styles.buttonClose]}
onPress={() => setModalVisible(!modalVisible)}
>
<Text style={styles.textStyle}>Hide Modal</Text>
</TouchableOpacity>
</View>
</View>
</Modal>
</>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
backgroundColor: 'black',
},
item: {
backgroundColor: '#FFF',
},
viewOne: {
flexDirection: 'row'
},
viewTwo: {
alignItems: 'flex-end', marginEnd: 9
},
title: {
fontSize: 16, // Semibold #000000
color: '#000000',
},
noOff: {
color: '#D65D35',
fontSize: 20, // Semibold
}, product: {
color: '#A6A6A6',
fontSize: 16, // Regular
}, titleView: {
flex: 1,
alignSelf: 'center',
marginStart: 14,
marginEnd: 14,
},
centeredView: {
flex: 1,
justifyContent: "center",
alignItems: "center",
marginTop: 22
},
modalView: {
margin: 20,
backgroundColor: "white",
borderRadius: 20,
padding: 10,
alignItems: "center",
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 2
},
shadowOpacity: 0.25,
shadowRadius: 4,
elevation: 5
},
button: {
borderRadius: 20,
padding: 10,
elevation: 2
},
buttonOpen: {
backgroundColor: "#F194FF",
},
buttonClose: {
backgroundColor: "#2196F3",
},
textStyle: {
color: "white",
fontWeight: "bold",
textAlign: "center"
},
modalText: {
marginBottom: 15,
textAlign: "center"
},
preview: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center',
},
capture: {
flex: 0,
backgroundColor: '#fff',
borderRadius: 5,
padding: 15,
paddingHorizontal: 20,
alignSelf: 'center',
margin: 20,
},
});

FlatList in React Native does not display any content

I just learned that there is a flatList in React Native. I have a list of services, when the user tap on each service, they are redirected to the address where those services are available. I am trying to display these addresses in FlatList. The screen shot of the list of services is below:
when the user taps on Test service, I want to show the address in the form of FlatList. I am not sure, but whatever I am displaying inside flatList is not showing on the page. Below is my entire code including flatlist:
/**
* Sample React Native App
* https://github.com/facebook/react-native
* #flow
*/
import React, { Component } from 'react';
import { Text, View, StyleSheet, Image, ScrollView, TouchableOpacity, Linking, Button, FlatList } from 'react-native';
import { connect } from 'react-redux';
import { getTheme } from 'react-native-material-kit';
import EvilIcon from 'react-native-vector-icons/EvilIcons';
import MaterialIcon from 'react-native-vector-icons/MaterialIcons';
import SimpleIcon from 'react-native-vector-icons/SimpleLineIcons';
import * as actions from '../actions';
import getDirections from 'react-native-google-maps-directions'
const theme = getTheme();
const styles = StyleSheet.create({
card: {
marginTop: 10,
paddingBottom: 20,
marginBottom: 20,
borderColor: 'lightgrey',
borderWidth: 0.5,
},
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#4F6D7A',
height: 500,
alignSelf:'center',
width:500,
position: 'relative',
marginTop: 5,
top: 10
},
title1: {
top: 10,
left: 80,
fontSize: 24,
},
title2: {
top: 35,
left: 82,
fontSize: 18,
},
image: {
flex: 0,
height: 100,
width: 333,
backgroundColor: 'transparent',
justifyContent: 'center',
alignItems: 'center',
},
closeIcon: {
position: 'absolute',
top: 5,
left: 295,
color: 'black'
},
icon: {
position: 'absolute',
top: 15,
left: 0
},
textArea: {
flexDirection: 'row',
paddingLeft: 20,
paddingTop: 10,
width: 260,
},
textIcons: {
color: '#26a69a',
},
actionArea: {
paddingTop: 10,
flexDirection: 'row',
justifyContent: 'space-around',
alignItems: 'center',
},
title:{
justifyContent: 'center',
paddingTop: 10,
alignItems: 'center',
alignSelf: 'center',
fontWeight: 'bold',
fontSize: 22,
color: 'black'
},
SerContent:{
fontWeight: 'bold',
fontSize: 16,
paddingTop: 10,
alignSelf: 'center',
color: 'black'
},
underLineText: {
fontSize: 17,
textDecorationLine: 'underline',
color: 'black',
fontWeight: 'bold',
alignSelf: 'center'
},
dir:{
flexDirection:'row',
paddingTop: 30,
alignSelf: 'center',
} ,
dirAddr:{
flexDirection:'column',
paddingTop: 30,
alignSelf: 'center'
},
Address1:{
alignSelf: 'center',
marginRight: 20,
fontSize: 17,
fontWeight: 'bold',
color: 'black'
},
fullAddress:{
marginRight: 20,
fontWeight: 'bold',
color: 'black'
},
toolbar:{
flexDirection:'row' , //Step 1
},
toolbarTitle:{
width: 10,
top: 0,
left: 0,
bottom: 0,
right: 0,
flex:1 //Step 3
},
buttonShape:{
margin: 40,
width:160,
marginLeft: 80,
backgroundColor:'#00BCD4',
},
producetBox:{
margin:10,
fontWeight:'bold',
color:'#000',
alignSelf:'center'
},
price:{
padding:5,
margin:10,
borderColor:'orange',
borderBottomWidth: StyleSheet.hairlineWidth,
}
});
class ServiceDetail extends Component {
handleClick = (link) => {
Linking.canOpenURL(link).then(suppported => {
if (supported) {
Linking.openURL(link);
} else {
console.log('Don\'t know how to open URI: ' + link);
}
});
};
constructor(props) {
super(props);
this.state = {
latitude: null,
longitude: null,
error: null,
};
}
componentDidMount()
{
navigator.geolocation.getCurrentPosition(
(position) => {
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null,
});
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
);
}
render() {
var online="";
var destUrl = 'https://www.google.com/maps/dir/Current+Location/' + this.props.services.destAddr1 ;
var destUrl1 ='https://www.google.com/maps/dir/Current+Location/' + this.props.services.destAddr2 ;
var Online= this.props.services.onlineURL;
return (
<View>
<View style={styles.toolbar}>
<Image
resizeMode='contain'
style={styles.toolbarTitle}
source={require('../Resources/AcrLogoWithDesc.jpg')} />
</View>
<View>
<Text style={styles.title}>{this.props.services.ser}</Text>
<Text style={styles.SerContent} >Service is available in the following locations:</Text>
</View>
<View>
<FlatList
data={this.props.services}
renderItem={({item})=>
<View>
<Text>{item.ser}</Text>
</View>
}
/>
</View>
<View style={styles.buttonShape}>
<Button onPress={() => this.props.noneSelected()} title = 'Close'/>
</View>
</View>
);
}
}
const mapStateToProps = state => {
return {
services: state.serviceSelected
};
};
export default connect(mapStateToProps, actions)(ServiceDetail);
I can see the content of {this.props.services.ser}, but I cannot see the content of <Text>{item.services.ser}</Text> which is inside the flatList. below is the screen shot of the service details when the user taps on Test service:
Item.services.serv content is not appearing on my second screen shot. Below is my JSON and the screen shot of resulting screen file":
[
{
"id":0,
"ser": "Test Service",
"Location": "TestLoc",
"Phone1":"(999)-999-5050",
"SecondLoc": "TestLoc2",
"email":"test#test.com",
"sourceLat":"33.977806",
"sourceLong":"-117.373261",
"destLatL1":"33.613355",
"destLongL1":"-114.596569",
"destLatL2":"33.761693",
"destLongL2":"-116.971169",
"destAddr1": "Test Address, Test Drive",
"destAddr2": "Test Address2, Test Drive2",
"onlineURL":"",
"Phone2": "(900)-900-3333"
},
]
[1]: https://i.stack.imgur.com/xiZMp.png
Any help will be highly appreciated. I tried below things for the flatList
<View>
<FlatList
data={this.props.services}
keyExtractor={(item, index) => item.services.id}
renderItem={({item})=>
<View>
<Text>{item.ser}</Text>
</View>
}
/>
</View>
This is another way that I tried:
<View>
<FlatList
style={{}}
data={this.props.services}
keyExtractor={(item, index) => item.key}
renderItem={(rowData) =>this.RenderFeedCard(rowData)}
/>
</View>
I assume that the JSON that you provide is for this.props.services. So the call inside renderItem={({item})=> {item.services.ser} should be {item.ser} instead.
The reason why is because Flatlist 'data' takes an array (eg: this.props.services) and 'renderItem' will take each item (this.props.services[0]) of the array and do something about it. So you only have to write {item.ser} in order to get the string.
renderItem={({item})=>(
<View>
<Text>{item.ser}</Text>
</View>
)}

Resources