Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing hardware back button android for React Native

I want to prevent the user from going back to the previous screen. So I added code, but this does not work. Are there any solutions for this? The alert pop up is seen but "return false" does not work.

componentDidMount() {    BackAndroid.addEventListener('hardwareBackPress', () => {      Alert.alert("alert","alert")        this.props.navigator.pop();         return false;    }); 
like image 700
Neethi Ratawa Avatar asked Oct 20 '16 04:10

Neethi Ratawa


People also ask

How do you prevent going back in React Native?

To make this work, you need to: Disable the swipe gesture for the screen ( gestureEnabled: false ). Override the native back button in the header with a custom back button ( headerLeft: (props) => <CustomBackButton {... props} /> ).

How would you handle the physical back button presses in Android React Native?

To handle the Android Back Button Press in the React Native we have to register the hardwareBackPress event listener with a callback function, which will be called after pressing the Back Button.

How do you handle the back button in React Native navigation?

By default React Navigation will handle the Android back button for you, however we'll need to override the defaults. If you're at the top of the stack and press the android back button the application will close. If you've navigated within the stack anywhere then the screen will pop.


1 Answers

You need to return true, if you want to disable the default back button behavior.

Here is a sample component which will block the user from going back to previous screen.

import React, {Component,} from 'react'; import {     View,     Text,     BackHandler,     ToastAndroid, } from 'react-native';  class BackButtonDemo extends Component {     componentDidMount() {         BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);     }      componentWillUnmount() {         BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);     }      handleBackButton() {         ToastAndroid.show('Back button is pressed', ToastAndroid.SHORT);         return true;     }      render() {         return (             <View>                 <Text>Back button example</Text>             </View>         );     } }  module.exports = BackButtonDemo; 

Note:

Also remove this.props.navigator.pop(); from your solution.

Navigator pop function will take the user to the previous screen rendered by Navigator.

like image 67
Jickson Avatar answered Sep 18 '22 00:09

Jickson