Reputation: 999
I am using React Navigation and I need some custom functionality when back button is pressed. Here is my code:
class AddEditIngredient extends Component {
constructor(props) {
super(props);
this.state = {
editStarted: false
};
this.goBack = () => {
if (this.state.editStarted === true) {
Alert.alert(
"Ingredient Not Saved",
"Do you want to navigate away without saving ingredient?",
[
{ text: "Cancel", onPress: () => null, style: "cancel" },
{ text: "Yes", onPress: () => this.props.navigation.goBack() }
],
{ cancelable: true }
);
} else {
this.props.navigation.goBack();
}
};
}
componentWillMount() {
BackHandler.addEventListener("hardwareBackPress", this.goBack);
}
componentWillUnmount() {
BackHandler.removeEventListener("hardwareBackPress", this.goBack);
}
My goBack function works fine for back button on screen, however when I try to press the physical back button it pops out all the screens and minimizes the application. From what I have gathered by reading previous posts on the issue, removeEventListener is not referring to the same function as addEventListener. So I tried this:
constructor(props) {
super(props);
this.state = {
editStarted: false
};
this.goBack = this.goBack.bind(this);
}
goBack = () => {
if (this.state.editStarted === true) {
Alert.alert(
"Ingredient Not Saved",
"Do you want to navigate away without saving ingredient?",
[
{ text: "Cancel", onPress: () => null, style: "cancel" },
{ text: "Yes", onPress: () => this.props.navigation.goBack() }
],
{ cancelable: true }
);
} else {
this.props.navigation.goBack();
}
};
But it didn't work. Can anyone point out my mistake?
Thanks
Upvotes: 2
Views: 4061
Reputation: 528
you need to attach return true
on your custom back listener or return false
to follow your parent handler
Upvotes: 1