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 \"
If you are using react-natigation then you need to use BackHandler
instead of BackAndroid
import { BackHandler } from 'react-native';
// code
componentDidMount() {
BackHandler.addEventListener('backPress');
}
// some more code
componentWillUnmount() {
BackHandler.removeEventListener('backPress');
}
I disable my back button (android) for whole application by add this code in App.js
componentDidMount() {
BackAndroid.addEventListener('hardwareBackPress', this.handleBackButton);
}
componentWillUnmount() {
BackAndroid.removeEventListener('hardwareBackPress', this.handleBackButton);
}
handleBackButton() {
return true;
}
don't forget to import BackAndroid
import {BackAndroid} from 'react-native'
Just to give you a complete answer when using react-navigation:
If you're using react-navigation, place the following in your RootNavigation class not the App.js in order to disable the back-button for the whole application.
import { BackHandler } from 'react-native';
componentDidMount() {
BackHandler.addEventListener('hardwareBackPress', this.onBackButtonPressed);
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.onBackButtonPressed);
}
onBackButtonPressed() {
return true;
}
Shiny new implementation using react hooks:
import React, {Component, useEffect} from 'react';
import {
View,
Text,
BackHandler,
ToastAndroid,
} from 'react-native';
const LogInView = () => {
useEffect(() => {
BackHandler.addEventListener('hardwareBackPress', () => true)
return () =>
BackHandler.removeEventListener('hardwareBackPress', () => true)
}, [])
return (
<View>
<Text>Back button example</Text>
</View>
);
}
export default LoginView
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
.
using the BackHandler from react native worked for me. Just include this line in your ComponentWillMount:
BackHandler.addEventListener('hardwareBackPress', function() {return true})
it will disable back button on android device.