[React-Native-Modal]: onBackButtonPress prop returns nothing - callback

I was trying to customize my Modal with onBackButtonPress prop. To check if it worked or not, I passed a console.log to it like this:
<Modal onBackButtonPress={() => console.log('Something')}>
<NewRidesModal
//...
/>
</Modal>
But in fact, it doesn't even return anything whenever I press the Android back button.
Why is he prop not returning any value at all? Is it deprecated?

I use this library too react-native-modal and onBackButtonPress is working fine.
I face another issue, in my case onBackdropPress is not working, but after I fix my styling modal, everything working fine.
This is my example,
Modal js
import React, { Component } from 'react'
import { View, Text, Image, TouchableOpacity } from 'react-native'
import styles from '../styles/StyleComponentModalProduct'
import { withNavigation } from 'react-navigation'
import Price from '../../../assets/components/price/Price'
import Modal from 'react-native-modal'
class ComponentModalProduct extends Component {
constructor(props) {
super(props)
this.state = {}
}
render() {
return (
<Modal
useNativeDriver={true}
animationIn={'fadeIn'}
animationOut={'fadeOut'}
backdropColor={'rgba(0, 0, 0, 0.7)'}
backdropOpacity={0.5}
isVisible={this.props.showProduct}
onSwipeComplete={() => this.props.close()}
swipeDirection={['down']}
style={{ justifyContent: 'flex-end', margin: 0 }}
onBackButtonPress={() => this.props.close()}
onBackdropPress={() => this.props.close()}>
<View style={styles.container}>
<View style={styles.subContainer}>
<View style={styles.headerContainer}>
<TouchableOpacity
onPress={() => this.props.close()}
style={styles.closButton}
/>
<View style={styles.containerImageProfile}>
<Image
resizeMode={'contain'}
style={styles.imageProfile}
source={{ uri: this.props.selectedProduct.foto }}
/>
</View>
<View style={styles.containerProfile}>
<View style={styles.containerTextName}>
<Text style={styles.textName}>
{this.props.selectedProduct.nama_produk}
</Text>
</View>
<Price
value={this.props.selectedProduct.harga_beli}
style={styles.textProfesi}
/>
</View>
</View>
</View>
</View>
</Modal>
)
}
}
export default withNavigation(ComponentModalProduct)
Style Modal js
import { StyleSheet, Dimensions } from 'react-native'
import { color } from '../../../assets/styles/ColorList'
import {
responsiveHeight,
responsiveFontSize,
responsiveWidth
} from 'react-native-responsive-dimensions'
const windowHeight = Dimensions.get('window').height
const styles = StyleSheet.create({
container: {
justifyContent: 'flex-end',
alignItems: 'center'
},
subContainer: {
height: windowHeight / 2,
backgroundColor: color.whiteColor,
width: '100%',
borderTopRightRadius: 20,
borderTopLeftRadius: 20,
paddingHorizontal: responsiveWidth(5),
paddingVertical: responsiveHeight(3)
},
headerContainer: {
justifyContent: 'center',
alignItems: 'center'
},
closButton: {
backgroundColor: '#E7E7E7',
height: 8,
width: 100,
marginVertical: 10
},
containerImageProfile: {
marginVertical: 10,
width: '100%',
justifyContent: 'center',
alignItems: 'center'
},
imageProfile: {
height: windowHeight / 3.5,
width: '90%',
borderRadius: 20
},
containerProfile: {
justifyContent: 'center',
alignItems: 'center'
},
containerTextName: {
marginHorizontal: responsiveWidth(10),
justifyContent: 'center'
},
textName: {
fontSize: responsiveFontSize(2.5),
color: color.fontColor,
textAlign: 'center'
},
textProfesi: {
fontSize: responsiveFontSize(2.5),
color: color.fontColor,
fontWeight: 'bold'
}
})
export default styles

I found out that onBackButtonPress is deprecated or it was actually removed. There should some more information about this on the documentation.

Related

React Native Axios fetching data from url error

import React, { Component } from 'react'
import { SafeAreaView, StyleSheet, StatusBar, ScrollView, View, Text, TextInput, Button, Alert } from 'react-native';
import axios from 'axios';
export default class Main extends Component {
constructor(props){
super(props)
this.state={
ifscCode:"",
detail:{}
}
}
ifscSearch = () => {
const tha = this;
x = `https://ifsc.razorpay.com/${this.state.ifscCode}`
console.log(x);
axios.get(`https://ifsc.razorpay.com/${this.state.ifscCode}`)
.then(function (response) {
tha.setState({detail:response.data})
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
}
render() {
return (
<>
<StatusBar barStyle="light-content" />
<SafeAreaView>
<ScrollView>
<View style={styles.maincnt}>
<View style={styles.inpcnt}>
<TextInput style={styles.txtinp} maxLength={11} placeholder='ifsc code search' onChange={(e)=>this.setState({ifscCode:e.target.value})} />
</View>
<View style={styles.btncnt}>
<Button title='Search' style={styles.btn} onClick={this.ifscSearch()} />
</View>
<View style={styles.listcnt}>
<Text>BANK: {this.state.detail.BANK}</Text>
</View>
<View>
</View>
</View>
</ScrollView>
</SafeAreaView>
</>
)
}
}
const styles = StyleSheet.create({
maincnt:{
flex:1,
margin: 10,
backgroundColor: 'white'
},
inpcnt:{
marginTop: 20,
},
btncnt:{
marginTop: 20,
},
listcnt:{
marginTop: 20
},
txtinp:{
width: 350,
height: 50,
borderRadius: 25,
borderWidth: 2,
borderColor: 'indigo',
alignSelf: 'center',
padding: 10
},
btn:{
width: 100,
height: 70,
alignSelf: 'center'
},
listcnt:{
marginTop: 50,
alignContent: 'center',
justifyContent: 'center'
}
});
You are having an error here
onClick={this.ifscSearch()}
please check out the below link to solve this issue.
https://stackoverflow.com/a/66149805/10562665
Also I see a little type error here as well
tha.setState({detail:response.data})
change tha to this
Please tell us more in details what you actually need.

React Native - Google Autocomplete API

My problem is the Text result of descriptions is overlapping to each other. I do not know if this a bug, I just can't make it solve it. I tried anything about the styles but nothing works. I need help from other with different perspective. Thank you for taking time to read this.
Image of the overlapping texts:
I also get a warning about the unique key prop, just adding this issue because it might be related to my problem.
Image of the Warning key prop:
Here are my codes:
async onChangeDestination(destination) {
this.setState({ destination });
const apiUrl = `https://maps.googleapis.com/maps/api/place/autocomplete/json?key=${apiKey}
&input=${destination}&location=${this.state.focusedLocation.latitude},
${this.state.focusedLocation.longitude
}&radius=2000`;
try {
const result = await fetch(apiUrl);
const json = await result.json();
console.log(json);
this.setState({
predictions: json.predictions
});
} catch (err) {
console.log(err)
}
}
render() {
//For Prediction
const predictions = this.state.predictions.map(prediction => (
<View style={styles.descriptionContainer}>
<Text key={prediction.id} style={styles.descriptionText}>{prediction.description}</Text>
</View>
));
//For Marker
let marker = null;
if(this.state.locationChosen) {
marker = <MapView.Marker coordinate={this.state.markerPosition}/>
}
return(
<View style={styles.container}>
{/* <StatusBar backgroundColor={'transparent'} translucent={true}/> */}
<MapView
style={styles.map}
initialRegion={this.state.focusedLocation}
onPress={this.pickLocationHandler}
showsUserLocation={true}
ref={ref => this.map = ref} //For animating map movement
>
{marker}
</MapView>
{/* <TouchableOpacity onPress={this.getLocationHandler} style={styles.iconContainer}>
<Icon name="md-locate" size={30} color="blue"/>
</TouchableOpacity> */}
<TextInput
placeholder="Search for an event or place!"
style={styles.destinationInput}
onChangeText={destination => {
this.setState({destination});
this.onChangeDestinationDebounced(destination)
}}
value={this.state.destination}
/>
{predictions}
</View>
);
}
const styles = StyleSheet.create({
container: {
zIndex: -1,
alignItems: 'center',
},
map: {
height: '100%',
width: '100%'
},
iconContainer: {
position: 'absolute',
top: 60,
right: 15,
zIndex: 1
},
destinationInput: {
position: 'absolute',
zIndex: 10,
width: '97%',
top: 15,
backgroundColor: 'white',
borderRadius: 8,
padding: 8
},
descriptionText: {
color: 'black',
position: 'absolute',
zIndex: 10,
top: 60,
},
descriptionContainer: {
zIndex: 2,
position: 'absolute',
top: 20,
height: Dimensions.get('window').height,
width: Dimensions.get('window').width,
justifyContent: 'space-between'
}
})
So I haven't been able to run the code, however your descriptionText style has position: 'absolute'. The behaviour you are seeing is therefor expected, as each text is placed on the same 'absolute' position. Removing this should give you the result you want.
The key warning is thrown as your descriptionContainer View is the root element in the map function, so this should have the key. Hopefully this helps, updated source code below with a small disclaimer that I wasn't able to test it.
async onChangeDestination(destination) {
this.setState({ destination });
const apiUrl = `https://maps.googleapis.com/maps/api/place/autocomplete/json?key=${apiKey}
&input=${destination}&location=${this.state.focusedLocation.latitude},
${this.state.focusedLocation.longitude
}&radius=2000`;
try {
const result = await fetch(apiUrl);
const json = await result.json();
console.log(json);
this.setState({
predictions: json.predictions
});
} catch (err) {
console.log(err)
}
}
render() {
//For Prediction
const predictions = this.state.predictions.map(prediction => (
<Text key={prediction.id} style={styles.descriptionText}>{prediction.description}</Text>
));
//For Marker
let marker = null;
if(this.state.locationChosen) {
marker = <MapView.Marker coordinate={this.state.markerPosition}/>
}
return(
<View style={styles.container}>
{/* <StatusBar backgroundColor={'transparent'} translucent={true}/> */}
<MapView
style={styles.map}
initialRegion={this.state.focusedLocation}
onPress={this.pickLocationHandler}
showsUserLocation={true}
ref={ref => this.map = ref} //For animating map movement
>
{marker}
</MapView>
{/* <TouchableOpacity onPress={this.getLocationHandler} style={styles.iconContainer}>
<Icon name="md-locate" size={30} color="blue"/>
</TouchableOpacity> */}
<TextInput
placeholder="Search for an event or place!"
style={styles.destinationInput}
onChangeText={destination => {
this.setState({destination});
this.onChangeDestinationDebounced(destination)
}}
value={this.state.destination}
/>
{this.state.predictions && this.state.predictions.length > 0 && (
<View style={styles.descriptionContainer}>{predictions}</View>
)}
</View>
);
}
const styles = StyleSheet.create({
container: {
zIndex: -1,
alignItems: 'center',
},
map: {
height: '100%',
width: '100%'
},
iconContainer: {
position: 'absolute',
top: 60,
right: 15,
zIndex: 1
},
destinationInput: {
position: 'absolute',
zIndex: 10,
width: '97%',
top: 15,
backgroundColor: 'white',
borderRadius: 8,
padding: 8
},
descriptionText: {
color: 'black',
},
descriptionContainer: {
zIndex: 2,
position: 'absolute',
top: 20,
height: Dimensions.get('window').height,
width: Dimensions.get('window').width,
}
})

Focus pseudo-class in Material ui

I am trying to apply some styles when a material-ui form control gets focus.
The pseudo-class 'hover' works well in the code below but 'focus' does not.
I am assuming that clicking into the Input component gives it focus but that does not seem to work. Any idea why and how to make it work?
import withStyles from "#material-ui/core/styles/withStyles"
import Input from "#material-ui/core/Input"
import InputLabel from "#material-ui/core/InputLabel"
import FormControl from "#material-ui/core/FormControl"
const styles = theme => ({
root: {
border: "1px solid",
borderRadius: theme.shape.borderRadius,
borderColor: "rgba(0, 0, 0, 0.23)",
marginBottom: theme.spacing.unit * 2,
padding: theme.spacing.unit,
width: "100%",
display: "flex",
flexDirection: "row",
alignItems: "center",
"&:focus": {
backgroundColor: "blue"
}
}
})
class TagsComponent extends React.Component {
render() {
return (
<FormControl variant="outlined">
<InputLabel>Tags</InputLabel>
<Input
disableUnderline
classes={{
root: this.props.classes.root
}}
/>
</FormControl>
)
}
}
export default withStyles(styles)(TagsComponent)
You can apply styles by overriding styles for input or override class name focused
const styles = {
...,
focused: {
backgroundColor: "green"
},
input: {
"&:focus": {
backgroundColor: "blue",
color: "white"
}
}
}
<Input
disableUnderline
classes={{
root: classes.root,
focused: classes.focused,
input: classes.input
}}
/>
Sandbox example https://codesandbox.io/embed/gallant-pascal-rh8jc

Get all the image shots from dibbbler API

I am trying to learn react-native, I just start working on this project two days ago.
I have kind of confusing in how to get the all the image shots from dibbbler API and display it on my android emulator.
This is what I have done,
'use strict';
import React, {
AppRegistry,
Component,
Image,
ListView,
StyleSheet,
View,
} from 'react-native';
var API_URL = 'https://api.dribbble.com/v1/shots';
class myproject extends Component {
constructor(props) {
super(props);
this.state = {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
}),
loaded: false,
};
}
componentDidMount() {
this.fetchData();
}
fetchData() {
fetch(API_URL)
.then((response) => response.json())
.then((responseData) => {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(responseData.images.treaser),
loaded: true,
});
})
.done();
}
render() {
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this.rendershots}
style={styles.listView}
/>
);
}
rendershots(shots) {
return (
<View style={styles.container}>
<Image
source={{uri: shots.images.treas}}
style={styles.images.treas}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
rightContainer: {
flex: 1,
},
treas: {
width: 53,
height: 81,
},
listView: {
paddingTop: 20,
backgroundColor: '#F5FCFF',
},
});
AppRegistry.registerComponent('myproject', () => myproject);
You need to provide credentials to retrieve the pictures from dribble.
You can register your app here to get credentials then use them to use the Dribbble API.

React Native navigator ref property

I am trying to follow the example (https://github.com/facebook/react-native/tree/master/Examples/UIExplorer/Navigator) on the react native site to set up my navigator, but I can't seem to get it to work. Right now I am having trouble with the ref property, as when its calls _setNavigatorRef, I am getting an error that it cannot find the property _navigator of null in the following code. It works in the example but I am not sure why:
index.ios.js
'use strict';
var React = require('react-native');
var DataEntry = require('./app/DataEntry');
var PasswordView = require('./app/PasswordView');
var GoogSignIn = require('./app/GoogSignIn');
var {
AppRegistry,
Image,
StyleSheet,
Text,
View,
Navigator,
TouchableOpacity,
} = React;
class PasswordRecovery extends React.Component {
render() {
return (
<Navigator
ref={this._setNavigatorRef}
style={styles.container}
initialRoute={{id: 'GoogSignIn', name: 'Index'}}
renderScene={this.renderScene}
configureScene={(route) => {
if (route.sceneConfig) {
return route.sceneConfig;
}
return Navigator.SceneConfigs.FloatFromRight;
}} />
);
}
renderScene(route, navigator) {
switch (route.id) {
case 'GoogSignIn':
return <GoogSignIn navigator={navigator} />;
case 'DataEntry':
return <DataEntry navigator={navigator} />;
case 'PasswordView':
return <PasswordView navigator={navigator} />;
default:
return this.noRoute(navigator);
}
noRoute(navigator) {
return (
<View style={{flex: 1, alignItems: 'stretch', justifyContent: 'center'}}>
<TouchableOpacity style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}
onPress={() => navigator.pop()}>
<Text style={{color: 'red', fontWeight: 'bold'}}>ERROR: NO ROUTE DETECTED</Text>
</TouchableOpacity>
</View>
);
}
_setNavigatorRef(navigator) {
if (navigator !== this._navigator) {
this._navigator = navigator;
if (navigator) {
var callback = (event) => {
console.log(
`TabBarExample: event ${event.type}`,
{
route: JSON.stringify(event.data.route),
target: event.target,
type: event.type,
}
);
};
// Observe focus change events from the owner.
this._listeners = [
navigator.navigationContext.addListener('willfocus', callback),
navigator.navigationContext.addListener('didfocus', callback),
];
}
}
}
componentWillUnmount() {
this._listeners && this._listeners.forEach(listener => listener.remove());
}
}
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('PasswordRecovery', () => PasswordRecovery);
I am just trying to get this all setup so that I can display a Google Sign in scene and then navigate from there. The code for that scene so far is here:
GoogSignIn.js
'use strict';
var React = require('react-native');
var { NativeAppEventEmitter } = require('react-native');
var GoogleSignin = require('react-native-google-signin');
var cssVar = require('cssVar');
var { Icon } = require('react-native-icons');
var {
AppRegistry,
StyleSheet,
Text,
View,
TouchableOpacity,
TouchableHighlight,
PixelRatio,
Navigator,
} = React;
var NavigationBarRouteMapper = {
LeftButton: function(route, navigator, index, navState) {
if (index === 0) {
return null;
}
var previousRoute = navState.routeStack[index - 1];
return (
<TouchableOpacity
onPress={() => navigator.pop()}
style={styles.navBarLeftButton}>
<Text style={[styles.navBarText, styles.navBarButtonText]}>
{previousRoute.title}
</Text>
</TouchableOpacity>
);
},
RightButton: function(route, navigator, index, navState) {
return (
null
);
},
Title: function(route, navigator, index, navState) {
return (
<Text style={[styles.navBarText, styles.navBarTitleText]}>
GOOGLE SIGN IN
</Text>
);
},
};
class GoogSignin extends React.Component {
constructor(props) {
super(props);
this.state = {
user: null
};
}
componentWillMount() {
var navigator = this.props.navigator;
var callback = (event) => {
console.log(
`NavigationBarSample : event ${event.type}`,
{
route: JSON.stringify(event.data.route),
target: event.target,
type: event.type,
}
);
};
// Observe focus change events from this component.
this._listeners = [
navigator.navigationContext.addListener('willfocus', callback),
navigator.navigationContext.addListener('didfocus', callback),
];
}
componentWillUnmount() {
this._listeners && this._listeners.forEach(listener => listener.remove());
}
componentDidMount() {
this._configureOauth(
'105558473349-7usegucirv10bruohtogd0qtuul3kkhn.apps.googleusercontent.com'
);
}
renderScene(route, navigator) {
console.log("HERE");
return (
<View style={styles.container}>
<TouchableHighlight onPress={() => {this._signIn(); }}>
<View style={{backgroundColor: '#f44336', flexDirection: 'row'}}>
<View style={{padding: 12, borderWidth: 1/2, borderColor: 'transparent', borderRightColor: 'white'}}>
<Icon
name='ion|social-googleplus'
size={24}
color='white'
style={{width: 24, height: 24}}
/>
</View>
<Text style={{color: 'white', padding: 12, marginTop: 2, fontWeight: 'bold'}}>Sign in with Google</Text>
</View>
</TouchableHighlight>
</View>
);
}
render() {
return (
<Navigator
debugOverlay={false}
style={styles.appContainer}
renderScene={this.renderScene}
navigationBar={
<Navigator.NavigationBar
routeMapper={NavigationBarRouteMapper}
style={styles.navBar}/>
}/>
);
}
_configureOauth(clientId, scopes=[]) {
console.log("WE HERE")
GoogleSignin.configure(clientId, scopes);
NativeAppEventEmitter.addListener('googleSignInError', (error) => {
console.log('ERROR signin in', error);
});
NativeAppEventEmitter.addListener('googleSignIn', (user) => {
console.log(user);
this.setState({user: user});
});
return true;
}
_signIn() {
GoogleSignin.signIn();
}
_signOut() {
GoogleSignin.signOut();
this.setState({user: null});
}
};
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
messageText: {
fontSize: 17,
fontWeight: '500',
padding: 15,
marginTop: 50,
marginLeft: 15,
},
button: {
backgroundColor: 'white',
padding: 15,
borderBottomWidth: 1 / PixelRatio.get(),
borderBottomColor: '#CDCDCD',
},
buttonText: {
fontSize: 17,
fontWeight: '500',
},
navBar: {
backgroundColor: 'white',
},
navBarText: {
fontSize: 16,
marginVertical: 10,
},
navBarTitleText: {
color: cssVar('fbui-bluegray-60'),
fontWeight: '500',
marginVertical: 9,
},
navBarLeftButton: {
paddingLeft: 10,
},
navBarRightButton: {
paddingRight: 10,
},
navBarButtonText: {
color: cssVar('fbui-accent-blue'),
},
scene: {
flex: 1,
paddingTop: 20,
backgroundColor: '#EAEAEA',
},
});
module.exports = GoogSignin;
I suspect it's a context issue. On your Navigator component, try converting from this:
ref={this._setNavigatorRef}
To this:
ref={(navigator) => this._setNavigatorRef(navigator)} (prettier IMHO)
or this:
ref={this._setNavigatorRef.bind(this)}