I am new to react native and firebase. I want to make a search bar that can search all data from firebase according to Barcode value, but I'm facing some errors while doing it. I think that my code is wrong somewhere but don't know where. I have transferred the firebase credentials to dbConfig.js . Here is my firebase data firebase data and my code:
import React,{Component} from 'react';
import { View, Text,TextInput,StyleSheet,Image, Button} from 'react-native';
import firebase from './dbConfig';
export default class ListItem extends Component {
render() {
return (
<>
<View style={styles.BackGround}>
<View style={styles.SectionStyle}>
<Image
source={require('./mic.png')} //mic image here
style={styles.ImageStyle}
/>
<TextInput
style={{ flex: 1, justifyContent: 'center', textAlign: 'center', fontSize: 12}}
placeholder="Search for Product"
underlineColorAndroid="transparent"
//onChangeText={(text) => this.setState({data: text})}
onSubmitEditing = {(text)=> this.setState({data: text})}
value = {this.state.data}
// onSubmitEditing={()=>this._search}
//onSubmitEditing={()=>this.componentWillMount}
/>
<Image
source={require('./usr.png')} //icon image here
style={styles.ImageStyle2}
/>
</View>
<View>
<Text>{this.state.items}</Text>
</View>
</View>
</>
);
}
constructor(props){
super(props);
this.state= {
items: '',
data: '',
};
}
componentWillMount(){
var ref = firebase.database().ref('/');
ref.child(this.state.data).on("value", snapshot =>{
console.log(snapshot.val().info.Price);
//if(snapshot.val().Price == this.state.data){
//this.setState({items: Object.values(snapshot.val())});
//}
//else{
//alert('there is problem');
//}
});
}
}
const styles = StyleSheet.create({
BackGround: {
backgroundColor: '#22abb6',
height: '100%'
},
SectionStyle: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
// borderWidth: 0.8,
// borderColor: '#000',
shadowColor:'#176f75',
marginTop: 50,
height: 40,
borderRadius: 10,
margin: 10,
},
ImageStyle: {
padding: 10,
marginLeft: 10,
margin: 5,
height: 25,
width: 25,
resizeMode: 'stretch',
alignItems: 'center',
},
ImageStyle2: {
padding: 10,
marginLeft: 10,
marginRight: 10,
margin: 5,
height: 25,
width: 25,
resizeMode: 'stretch',
alignItems: 'center',
},
});
I did it by changing the follows:
//adding this in TextInput
onSubmitEditing = {this.componentWillMount}
//on changing the function compoundWillMount to async()
componentWillMount= async()=>{
Related
I have created a simple program to display information from my website on the app. It works on iOS but on my Android device an error shows up :
posts.map is not a function. This is my code:
import React, { Component } from 'react';
import {
View,
Text,
ActivityIndicator,
ScrollView,
StyleSheet,
Image,
Header,
} from 'react-native';
let lw = 100;
import Img from 'react-image';
let li = 'https://www.teanewsnetwork.com/profileicons/';
let bean = 'azure.jpg';
export default class App extends Component {
state = {
loading: true,
error: false,
posts: [],
};
componentWillMount = async () => {
try {
const response = await fetch(
'https://www.teanewsnetwork.com/api/fetcharticles.php?code=#NIL7*GKD60JTRTEFZ0CkvpHMJJW^-9q&starting=0&limit=40'
);
const posts = await response.json();
this.setState({ loading: false, posts });
} catch (e) {
this.setState({ loading: false, error: true });
}
};
renderPost = ({ id, title, content, authorimage, authorname }, i) => {
let b = { authorname };
return (
<View style={styles.postContent}>
<View
style={{
flex: 1,
flexDirection: 'column',
textAlign: 'center',
justifyContent: 'center',
alignItems: 'center',
}}>
<Text style={styles.postauthor}>{title} </Text>
<Image
source={{
uri: `https://teanewsnetwork.com/profileicons/${authorimage}`,
}}
defaultSource={require('./contact-outline.png')}
style={{
width: lw,
height: lw,
flex: 1,
justifyContent: 'center',
alignItems: 'center',
borderRadius: lw / 2,
}}
/>
<Text style={styles.postauthor}>{authorname}</Text>
</View>
<Text style={styles.postBody}>{content}</Text>
</View>
);
};
render() {
const {posts, loading, error} = this.state
if (loading) {
return (
<View style={styles.center}>
<ActivityIndicator animating={true} />
</View>
)
}
if (error) {
return (
<View style={styles.center}>
<Text>
Failed to load posts!
</Text>
</View>
)
}
return (
<ScrollView style={styles.container}>
{posts.map(this.renderPost)}
</ScrollView>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
borderBottomWidth: 0,
borderBottomColor: 'red',
top: 100,
zIndex: 6,
},
postauthor: {
flex: 1,
borderBottomWidth: 0,
borderBottomColor: 'red',
paddingVertical: 25,
fontSize: 18,
paddingRight: 15,
left: 10,
justifyContent: 'center',
alignItems: 'center',
textAlign: 'center',
},
postContent: {
flex: 1,
borderBottomWidth: 20,
borderBottomColor: '#EEE',
borderRadius: 4,
fontSize: 18,
left: 0,
paddingRight: 15,
justifyContent: 'center',
alignItems: 'center',
textAlignVertical: 'center',
textAlign: 'center',
},
postBody: {
marginTop: 1,
fontSize: 18,
color: 'black',
left: 10,
textAlign: 'center',
},
center: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
I am a beginner coder on react native and would like to have some help here. The code works on iOS emulator with EXPO but doesnt work on my Android Device.
Thanks in Advance!
Most likely posts is not a array, check the type of posts.
I am using react-native-simple-picker in my app which works fine in my project if I use the default show button but I would like to show the picker when I use a different button in my project. It looks like this.refs.picker.show() in ProposalPicker.js is the function that needs to be called, but I am not sure how to access this from another component file. Currently my code results in the following error - `Cannot read property 'show' of undefined. Appreciate any help.
ProposalPicker.js
import React, { Component } from 'react';
import { Picker, View, Text } from 'react-native';
import Button from './Button';
import SimplePicker from 'react-native-simple-picker';
const options = ['Option1', 'Option2', 'Option3'];
// Labels is optional
const labels = ['Banana', 'Apple', 'Pear'];
class ProposalPicker extends Component {
constructor(props) {
super(props);
this.state = {
selectedOption: '',
};
}
render() {
return (
<View style={styles.container}>
<Text style={styles.paragraph}>Current Option: {this.state.selectedOption}</Text>
<Text
style={{ color: '#006381', marginTop: 20 }}
onPress={() => {
this.refs.picker.show();
}}
>
Click here to select your option
</Text>
<Text
style={{ color: '#006381', marginTop: 20 }}
onPress={() => {
this.refs.picker2.show();
}}
>
Click here to select your option with labels
</Text>
<SimplePicker
ref={'picker'}
options={options}
onSubmit={(option) => {
this.setState({
selectedOption: option,
});
}}
/>
<SimplePicker
ref={'picker2'}
options={options}
labels={labels}
itemStyle={{
fontSize: 25,
color: 'red',
textAlign: 'left',
fontWeight: 'bold',
}}
onSubmit={(option) => {
this.setState({
selectedOption: option,
});
}}
/>
</View>
);
}
}
// class ProposalPicker extends Component {
// state={proposal: ''}
// selectedValue = '';
// updateProposal = (proposal) => {
// this.setState({ proposal: this.selectedValue });
// }
// handleConfirmClick = () => {
// this.setState({ proposal: this.selectedValue });
// }
// render() {
// return (
// <View>
// <Picker selectedValue = {this.selectedValue}
// onValueChange = {this.updateProposal}
// itemStyle={{ backgroundColor: 'grey' }}
// >
// <Picker.Item label = "Test" value = "TestValue1" />
// <Picker.Item label = "Test 1" value = "TestValue2" />
// <Picker.Item label = "Test" value = "TestValue3" />
// <Picker.Item label = "Test" value = "TestValue4" />
// <Picker.Item label = "Test" value = "TestValue5" />
// <Picker.Item label = "Test" value = "TestValue6" />
// <Picker.Item label = "Test" value = "TestValue7" />
// <Picker.Item label = "Test" value = "TestValue8" />
// <Picker.Item label = "Test nothing" value = "TestValue9" />
// </Picker>
// <Text style = {styles.textStyle}>CONFIRM</Text>
// </View>
// )
// }
// }
const styles = {
proposalPickerStyle: {
backgroundColor: 'lightgrey'
},
textStyle: {
flex: 1
}
}
export default ProposalPicker;
ProposalPickerButton.js
import React from 'react';
import { View, Text, Image, TouchableOpacity } from 'react-native';
const PickerButton = ({ onPress, text }) => {
const { textStyle, iconStyle, iconContainerStyle, textContainerStyle, buttonStyle } = styles;
return (
<TouchableOpacity onPress={onPress} style={buttonStyle}>
<View style={styles.containerStyle}>
<View style={iconContainerStyle}>
<Image
style={iconStyle}
source={require('./images/201.png')}
/>
</View>
<View style={textContainerStyle}>
<Text style={textStyle}>{text}</Text>
</View>
<View style={iconContainerStyle}>
<Image
style={iconStyle}
source={require('./images/201.png')}
/>
</View>
</View>
</TouchableOpacity>
);
}
const styles = {
containerStyle: {
flex: 1,
//backgroundColor: 'red',
borderWidth: 2,
borderRadius: 0,
borderColor: '#FFFFFF',
//shadowColor: '#000',
//shadowOffset: { width: 0, height: 2 },
//shadowOpacity: 0.1,
//shadowRadius: 2,
//elevation: 1,
marginLeft: 40,
marginRight: 40,
marginTop: 10,
marginBottom: 10,
justifyContent: 'center',
alignItems: 'center',
flexDirection: 'row'
},
iconContainerStyle: {
flex: 2,
//backgroundColor: 'blue',
justifyContent: 'center',
//alignItems: 'center',
//width: '20%',
//height: '20%'
},
iconStyle: {
flex: 1,
width: null,
height: null,
resizeMode: 'contain',
marginLeft: 10,
marginRight: 10,
marginTop: 10,
marginBottom: 10
},
textContainerStyle: {
flex: 8,
//backgroundColor: 'orange',
alignItems: 'flex-start',
justifyContent: 'center',
},
textStyle: {
fontSize: 20,
fontWeight: 'bold',
color: '#FFFFFF',
//marginLeft: 10
//padding: 18
},
buttonStyle: {
width: '100%',
height: '100%'
}
};
export default PickerButton;
App.js
import React, { Component } from 'react';
import { View, Text, ImageBackground } from 'react-native';
import Logo from './Logo';
import ProposalPickerButton from './ProposalPickerButton';
import Button from './Button';
import ProposalPicker from './ProposalPicker';
import SimplePicker from 'react-native-simple-picker';
class App extends Component {
render() {
return (
<ImageBackground
source={require('./images/city.png')}
style={styles.backgroundStyle}
>
<View style={styles.backgroundOverlayStyle} />
<View style={styles.container}>
<View style={styles.logoContainer}>
<Logo />
</View>
<View style={styles.proposalPickerButtonStyle}>
<ProposalPickerButton
onPress={() => new ProposalPicker().refs.picker.show()}
// onPress={() => console.log('Proposal picker button pressed')}
//onPress={() => Linking.openURL(url)}
text="Select a service line"
/>
</View>
<View style={styles.startProposalButtonStyle}>
<Button text="Start proposal"/>
</View>
<View style={styles.proposalPickerStyle}>
{/* <ProposalPicker /> */}
</View>
</View>
</ImageBackground>
);
}
}
const styles = {
backgroundStyle: {
flex: 1,
backgroundColor: '#000000',
width: '100%',
height: '100%',
position: 'absolute'
},
backgroundOverlayStyle: {
flex: 1,
position: 'absolute',
backgroundColor: '#003284',
opacity: 0.5,
width: '100%',
height: '100%'
},
container: {
//backgroundColor: 'red',
flex: 1,
//opacity: 0.5,
alignItems: 'center',
width: '100%',
height: '65%',
},
logoContainer: {
//backgroundColor: 'blue',
flex: 3,
alignItems: 'center',
justifyContent: 'center',
width: '100%',
height: '65%',
},
proposalPickerButtonStyle: {
flex: 1,
//backgroundColor: 'yellow',
alignItems: 'center',
justifyContent: 'center',
width: '100%',
height: '100%',
marginLeft: 100,
marginRight: 100
},
startProposalButtonStyle: {
flex: 1,
//backgroundColor: 'purple',
width: '100%',
height: '100%',
marginTop: 10,
marginRight: 80
},
proposalPickerStyle: {
opacity: 1,
flex: 2,
backgroundColor: 'green',
width: '100%',
height: '100%'
},
};
export default App;
To call methods via refs you need to have a ref assigned to an already mounted component. Therefore you can't say new ProposalPicker().refs.picker.show() because refs.picker does not exist until the component is mounted. You Should have your button and picker components in the same parent, that way you can easily create a ref in that parent, assign it, and call methods from it:
Also you should use callback refs instead of string refs because string refs are deprecated. In that case it would look like:
constructor(props){
super(props)
this.state = ...
this.picker = React.createRef() // make the ref
}
Then assign the ref:
<SimplePicker
ref={this.picker}
And then you can make an function to call when your button is pressed:
showPicker = () => {
if (this.picker.current) {
this.picker.current.show()
}
}
I am trying to place an Avatar element over my TextInput so that it will look like a conventional search bar, but it doesn't go over the TextInput Please isn't it working, or can another better method of putting the search icon over the TextInput be suggested, Thank you
import { Avatar } from 'react-native-elements';
import FontAwesome
from './node_modules/#expo/vector-icons/fonts/FontAwesome.ttf';
import MaterialIcons
from './node_modules/#expo/vector-icons/fonts/MaterialIcons.ttf';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {timePassed: false};
}
state = {
fontLoaded: false
};
async componentWillMount() {
try {
await Font.loadAsync({
FontAwesome,
MaterialIcons
});
this.setState({ fontLoaded: true });
} catch (error) {
console.log('error loading icon fonts', error);
}
}
render() {
setTimeout(() => {
this.setState({timePassed: true})
}, 4000);
if (!this.state.timePassed) {
return <Splash/>;
} else {
return (
<View style={BackStyles.container}>
<Avatar style={BackStyles.searchIcon} icon={{ name: 'search', size: 25, }}/>
<TextInput placeholder="Search for your herbs.."
underlineColorAndroid={'transparent'} style={BackStyles.textBox}
/></View>
);
}
}
}
const BackStyles = StyleSheet.create({
container: {
flexDirection: 'row',
alignItems: 'flex-start',
alignSelf: 'stretch',
flex: 1,
backgroundColor: '#E2E2E2',
marginTop: 20,
// width: '100%'
},
textBox: {
flex: 1,
height: 45,
padding: 4,
// textAlignVertical: 'top',
paddingLeft: 20,
// marginRight: 5,
flexGrow: 1,
// fontSize: 18,
color: '#000',
backgroundColor: '#fff',
// textAlign: 'center'
},
searchIcon:{
position: 'absolute',
alignSelf: 'stretch',
height: 45,
flex: 1,
top: 50,
flexGrow: 1,
padding: 4
}
});
You can use Flexbox's justifyContent feature to force the TextInput to the left and the search icon to the right. If you put a border on the container and not the TextInput, the entire thing will appear as there is a search icon fixed onto the right of the TextInput, when, in reality, they are two separate components.
// styles
const styles = StyleSheet.create({
searchBox: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
borderWidth: 1,
borderColor: 'black',
},
});
// the component
<View style={styles.searchBox}>
<TextInput ...yourprops />
<Avatar ...yourprops />
</View>
If you want to read more about justifyContent and how godly Flexbox is, you should check out Chris Coyier's Flexbox guide.
I am studing react-native a 4 months and I am Build my App. I got problems with Camera. I am trying to take a picture, save and access the photo. I take a picture but I don't know where picture goes and how to acess.
I am using expo import camera, because when I use from react a get some error.
this is my code:
import React, {Component} from 'react';
import {Text, View, TouchableOpacity, Image,TouchableHighlight,Vibration} from 'react-native';
//import Camera from 'react-native-camera';
import {Camera, Permissions,} from 'expo';
const myStyle = {
container: {
flex: 1,
flexDirection: 'row',
},
preview: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center'
},
capture: {
flex: 0,
backgroundColor: '#fff',
borderRadius: 5,
color: 'red',
padding: 10,
margin: 40
},
main2: {
flex: 1,
//alignItems: 'flex-start',
flexDirection: 'row',
justifyContent: 'space-between',
},
main: {
flex: 1,
},
borda: {
//flex: 0.1,
alignItems: 'flex-end',
backgroundColor: 'black',
height: 110,
},
borda2: {
backgroundColor: 'black',
width: 60,
},
borda3: {
width: 60,
backgroundColor: 'black',
},
borda4: {
height: 120,
backgroundColor: 'black',
//flex: 1,
alignItems: 'center',
flexDirection: 'row',
justifyContent:'space-between',
},
texto:{
fontSize: 18,
marginBottom: 40,
color: 'white',
},
textoButton:{
fontSize: 18,
color: 'white',
marginTop: 5,
},
button:{
alignSelf: 'flex-end',
alignItems: 'center',
backgroundColor:'transparent',
flexDirection: 'row',
justifyContent:'space-between'
},
cameraStyle:{
width: 70,
height: 57,
//margin:30,
alignItems: 'center',
tintColor: 'white',
},
flipStyle:{
width: 52,
height: 57,
marginLeft:10,
alignItems: 'center',
tintColor: 'white',
},
gallerystyle:{
width: 64,
height: 57,
marginLeft:10,
alignItems: 'center',
tintColor: 'white',
marginRight: 10,
},
closeStyle:{
width: 56,
height: 57,
marginTop: 30,
marginRight: 20,
alignItems: 'flex-end',
tintColor: 'white',
justifyContent:'flex-end'
},
box:{
width: 'auto',
justifyContent: 'space-between',
flexDirection: 'column',
alignItems: 'center',
},
};
export default class CameraAcess extends Component {
constructor(props) {
super(props);
this.state = {hasCameraPermission: null, type: Camera.Constants.Type.back,};
}
async componentWillMount() {
const {status} = await Permissions.askAsync(Permissions.CAMERA);
this.setState({hasCameraPermission: status === 'granted'});
}
snap = async function(){
if (this.camera) {
this.camera.takePictureAsync().then(data => {
FileSystem.moveAsync({
from: data,
to: '${FileSystem.documentDirectory}photos/Photo_${this.state .photoId}.jpg',
}).then(() => {
this.setState({
photoId: this.state.photoId + 1,
});
Vibration.vibrate();
})
.catch((e) => {
console.log(e, 'ERROR');
});
})
.catch((e) => {
console.log(e, 'takePicture ERROR');
});
}
console.log('I took the picture');
};
cameraPhoto = require('./Images/camera.png');
flipPhoto = require('./Images/flip.png');
closePhoto = require('./Images/close.png');
galleryPhoto = require('./Images/gallery.png');
render() {
const { main,main2, borda, borda2, borda3,borda4,cameraStyle,flipStyle,closeStyle,box,textoButton,gallerystyle} = myStyle;
const {hasCameraPermission} = this.state;
if (hasCameraPermission === null) {
return <View/>;
} else if (hasCameraPermission === false) {
return <Text>No access to camera</Text>;
} else {
return (
<View style={main}>
<Camera style={main} type={this.state.type}>
<TouchableHighlight onPress={() => {this.props.navigator.push({id: 'MenuPrincipal'});}}
style={borda} underlayColor={'black'} activeOpacity={0.6}>
<Image source={this.closePhoto} style={[closeStyle]}/>
</TouchableHighlight>
<View style={main2}>
<View style={[borda2]}/>
<View style={[borda3]}/>
</View>
<View style={[borda4]}>
<TouchableOpacity onPress={() => {this.setState({type: this.state.type === Camera.Constants.Type.back
? Camera.Constants.Type.front : Camera.Constants.Type.back,});}}>
<View style={box}>
<Image source={this.flipPhoto} style={[flipStyle]}/>
<Text style={textoButton}>
Flip
</Text>
</View>
</TouchableOpacity>
<TouchableOpacity onPress={() => {this.snap()}}>
<View style={box}>
<Image source={this.cameraPhoto} style={[cameraStyle]}/>
<Text style={textoButton}>
Capture
</Text>
</View>
</TouchableOpacity>
<TouchableOpacity onPress={() => {false}}>
<View style={box}>
<Image source={this.galleryPhoto} style={[gallerystyle]}/>
<Text style={textoButton}>
Gallery
</Text>
</View>
</TouchableOpacity>
</View>
</Camera>
</View>
);
}
}
}
Someone help me to solve this problem and please be especific and clearly in your explanation, every details are necessary to me. I need this to end my App.
If I were you I would do
console.log(data);
then you can see what the promise returns in the XDE. You should, at the very least, see the following properties: height, width, uri. Uri will show you exactly where that image is being stored in the cache.
I am new to react native this is my first attempt in react native I was following a sample tutorial for the basic understanding of the code and other things I am following this raywenderlich's propertyfinder example, while implementing the first navigation example I am facing this issue:
undefined is not a function (evaluating 'this.props.renderScene(route,this)')
in my android device(Samsung J7) which I am using to run the app
Here is my index.android.js
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var SearchPage = require('./SearchPage');
var styles = ReactNative.StyleSheet.create({
text: {
color: 'black',
backgroundColor: 'white',
fontSize: 30,
margin: 80
},
container: {
flex: 1
}
});
class PropertyFinderApp extends React.Component {
render() {
return (
<ReactNative.Navigator
style={styles.container}
renderScene={this.renderScene}
initialRoute={{
component: SearchPage,
index:0,
title:"home"
}}/>
);
}
}
ReactNative.AppRegistry.registerComponent('PropertyFinder', function() { return PropertyFinderApp });`
and the SearchPage.js file(the other component which I am using):
'use strict';
import React, { Component } from 'react';
import {
StyleSheet,
Text,
TextInput,
View,
TouchableHighlight,
ActivityIndicator,
Image
} from 'react-native';
var styles = StyleSheet.create({
description: {
marginBottom: 20,
fontSize: 18,
textAlign: 'center',
color: '#656565'
},
container: {
padding: 30,
marginTop: 65,
alignItems: 'center'
},
flowRight: {
flexDirection: 'row',
alignItems: 'center',
alignSelf: 'stretch'
},
buttonText: {
fontSize: 18,
color: 'white',
alignSelf: 'center'
},
button: {
height: 36,
flex: 1,
flexDirection: 'row',
backgroundColor: '#48BBEC',
borderColor: '#48BBEC',
borderWidth: 1,
borderRadius: 8,
marginBottom: 10,
alignSelf: 'stretch',
justifyContent: 'center'
},
searchInput: {
height: 36,
padding: 4,
marginRight: 5,
flex: 4,
fontSize: 18,
borderWidth: 1,
borderColor: '#48BBEC',
borderRadius: 8,
color: '#48BBEC'
}
});
export default class SearchPage extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.description}>
Search for houses to buy!
</Text>
<Text style={styles.description}>
Search by place-name, postcode or search near your location.
</Text>
<View style={styles.flowRight}>
<TextInput
style={styles.searchInput}
placeholder='Search via name or postcode'/>
<TouchableHighlight style={styles.button}
underlayColor='#99d9f4'>
<Text style={styles.buttonText}>Go</Text>
</TouchableHighlight>
</View>
<TouchableHighlight style={styles.button}
underlayColor='#99d9f4'>
<Text style={styles.buttonText}>Location</Text>
</TouchableHighlight>
</View>
);
}
}
module.exports = SearchPage;
I have no idea what I am doing wrong since I am a beginner in this any help will be appreciated, thanx in advance.
You for got to write renderScene function, see following example:
<ReactNative.Navigator
...
renderScene={this.renderScene.bind(this)} />
renderScene(route, navigationOperations, onComponentRef) {
switch(route.index) {
case 0:
return <SearchPage />
}
}