Onpress with conditional will not call a function - react-native

I have some problem with onPress button function,
if I create button and calling function directly it work well,
but if I'm using conditional it will not call the function.
I already create 2 button below to simulate, button with title "submit normal" can call function and pass the property successfully, button with title "submit conditional" will not calling this.makeRemoteRequest.bind(this); but if you put alert it will react normally, nothing happen if calling a function.
<Input
containerStyle={{ width: '90%' }}
placeholder="Predefined User ID"
label="User ID"
labelStyle={{ marginTop: 16 }}
editable={false}
value={this.state.userid}
onChangeText={input_user_id => this.setState({ input_user_id })}
/>
<Input
containerStyle={{ width: '90%' }}
placeholder="Please fill services request notes here"
label="Reason"
labelStyle={{ marginTop: 16 }}
onChangeText={input_services_detail => this.setState({ input_services_detail })}
/>
<Button
title='Submit Conditional'
onPress={() => {
if (this.state.input_services_detail != null)
{
this.makeRemoteRequest.bind(this);
}
else
{
Alert.alert('Please fill the service detail first');
}
}}><Text style={styles.buttonText}>Submit Aset</Text>
</Button>
<Button
title='Submit Normal'
onPress={this.makeRemoteRequest.bind(this)}><Text style={styles.buttonText}>Submit Aset</Text>
</Button>
</View>
Expecting to call a function using conditional. Appreciate if somebody can brief me on this. Thanks before.

I would say this is kind of a bad practice to achieve this behaviour.
A better way to write it would be like this -
<Button
title='Submit Conditional'
onPress={this.onPressSubmitButton.bind(this)}>
<Text style={styles.buttonText}>Submit Aset</Text>
</Button>
Changed the name of the onPress function to onPressSubmitButton
And the onPressSubmitButton function -
onPressSubmitButton() {
if (this.state.input_services_detail === null) {
return Alert.alert('Please fill the service detail first')
}
this.makeRemoteRequest()
}
I think it more clear to read and understand.
Also you can write the function signature like this -
onPressSubmitButton = () => {
...
}
which make it bound already, this way you can call it like this -
<Button
title='Submit Conditional'
onPress={this.onPressSubmitButton}>
<Text style={styles.buttonText}>Submit Aset</Text>
</Button>

You're not calling this.makeRemoteRequest in your condition, you're just binding it. Change your conditional onPress prop like this :
onPress={this.state.input_services_detail != null ? this.makeRemoteRequest.bind(this) : () => Alert.alert('Please fill the service detail first')}
And you don't need the != null :
onPress={this.state.input_services_detail ? this.makeRemoteRequest.bind(this) : () => Alert.alert('Please fill the service detail first')}

Related

react native remove item from flatlist with confirmation in alert

i'm trying to remove an item from flatlist but before remove it there is an alert to ask "are you sure to remove it".
but i couldn't sure how to do it.
this is alert
<AwesomeAlert
show={showAlert}
title="UYARI!"
message="Are you sure to remove it?"
closeOnTouchOutside={false}
closeOnHardwareBackPress={false}
showCancelButton={true}
showConfirmButton={true}
cancelText="Hayır"
confirmText="Evet"
confirmButtonColor="#DD5555"
onCancelPressed={() => {
setShowAlert(false);
}}
onConfirmPressed={() => {
//what should i do here ?
setShowAlert(false);
}}
/>
this is flatlist render item
const barcodeList = barcodeArray => {
return (
<View style={styles.ListItemContainer}>
<Text>-{barcodeArray.item}</Text>
<TouchableOpacity onPress={() => removeItem(barcodeArray.item)}>
//this removeItem func is remove it without confirmation
<Text style={{fontSize: 20, fontWeight: 'bold'}}>X</Text>
</TouchableOpacity>
</View>
);
};
based on the item passed to removeItem function you can filter out the value and then set state.
eg
let filter_elements = item.filter(
item => item.id!= barcodeArray.item.id
);
setState(filter_elements)
Actually your alert component should return a promise.
Something like that:
const removeItem = id => {
alert("Are you sure?").then(if(value === "Yes") => {
// do some stuff here
})
}
You can write a async alert.
Can React native Alert wait for user response?

How to add an expression and an arrow function to onPress in react native?

I am trying to create a TouchableOpacity that executes another function and an arrow function, but cannot figure out a way to do so. Here is my code:
<SubmitButton
text="NEXT"
style={{ backgroundColor: "#093968" }}
onPress={
(handleSubmit,
() => this.setState({ submitPressed: true }))
}
/>
I understood that the second function is overriding the first, but how do I solve this problem. And I also don't want to add the arrow function to handleSubmit.
You can do:
<SubmitButton
text="NEXT"
style={{ backgroundColor: "#093968" }}
onPress={()=>{
handleSubmit()
this.setState({ submitPressed: true })
}}
/>

FlatList's renderItem doesn't recognise "this" keyword

So, I recently started making FlatList a recurring thing in the app I'm working on. I am right now working on a screen that gives a list of requests and is updated once one is accepted, which is done by pressing a button. There's a method called getNewRequests I am using to update the requests, but it can't seem to be called by the flatline, as it only returns the error TypeError: _this3 is undefined.
I really need that method to work, because I need to update the state of that screen, and trying to type the whole method there only returns the same error. In that context, this always returns undefined.
render(){
return(
<View style={GenericStyles.styles.genericContainer}>
<Text> REQUEST SCREEN </Text>
<FlatList
data={this.state.requestList}
renderItem={this.renderItem}
keyExtractor={item => item.id}
/>
<Button title="Voltar" color="cyan" onPress={() => this.props.navigation.goBack()}/>
</View>
);
}
renderItem({item}){
return(
<Card
containerStyle={{flex: 1, width: 200}}
title={item.Username}>
<Button color="blue" title="Accept" onPress={() => RequestService.allowRequest(item.id, (response) => {
let rsp = JSON.parse(response);
if(rsp.success){
this.getNewRequests();
}
})}/>
</Card>
);
}
You need to either bind the function in your constructor (or wherever you want) doing:
constructor(props){
super(props)
this.renderItem.bind(this)
}
or use arrow function:
renderItem = ({item}) => {
//your function
}
Doing this will give the function access to the this of the current component.

Passing values dynamically to child component react native

App.js
render() {
return (
<View style={{ flex: 1, marginTop: 20 }}>
<Button
title="Learn More"
color="#841584"
accessibilityLabel="Learn more about this purple button"
onPress={() => {
(this.state.dadda = '2017-09-07');
}}
/>
<EventCalendar
eventTapped={this._eventTapped.bind(this)}
events={this.state.events}
width={width}
initDate={this.state.dadda}
scrollToFirst={false}
/>
</View>
); }
This is my parent component ,I want to pass initDate to event calendar component,I want to update the date when the button is pressed?
You should not mutate the state by assigning value to the state variable directly but instead use setState to acheive that.
<Button
title="Learn More"
color="#841584"
accessibilityLabel="Learn more about this purple button"
onPress={() => this.setState({dadda: '2017-09-07'})}
/>
The way you are setting dadaa into the state is not correct, use this.setState function instead, have a look at the doc.
Change your onPress handler to
...
< Button
title = "Learn More"
color = "#841584"
accessibilityLabel = "Learn more about this purple button"
onPress = {
() => {
this.setState({
dadda:'2017-09-07'
});
}
}
/>
...
Also, don't declare the function inside render, rather keep it at the class level like
onPressHandler = () => {
this.setState({
dadaa: 'aaaa'
});
}
render() {
return (
...
<
Button
...
onPress = {this.onPressHandler}
...
/>
...
);
}
Hope this will help!

this.refs.FieldName.focus() is not a function in React Native

I am using Custom Keyboard. In that I am using CustomTextInput in place of TextInput. All works well but I want to focus input field in function.
<CustomTextInput customKeyboardType="hello"
onFocus={() => this.onFocus('fieldname')}
selectTextOnFocus={ true }
ref="TextInput"
underlineColorAndroid = 'transparent'
onChangeText={(value) => this.setState({fieldname:this.onChange(value)})}
/>
In Function something like below :-
function () {
Keyboard.dismiss();
this.refs.TextInput.focus();
}
But I am getting an error :- this.refs.TextInput.focus is not a function.
Basically my focus() function is not working.
Please help!
I tried this.refs['TextInput'].focus() and it works for me. You can write a function for Textinput's onFocus and within this function dimiss default keyboard, lunch your customized keyboard and focus again on your TextInput. I hope it will help.
This is my code:
<TextInput
style={{ height: 40, width: 200 }}
ref="TextInput"
/>
<TouchableOpacity
onPress={() => { (this.refs['TextInput'] as any).focus() }}>
<Text>Press to focus</Text>
</TouchableOpacity>