Home > Mobile >  How to use Backhandler in React-native
How to use Backhandler in React-native

Time:03-02

I can't exit the app When I even touch Android back button twice. just stuck in first bottom tab.

{input} is the order of button in the screen. There are four of button in the screen to go to each View.(in same class component)

handleBackButton() {
   this.setState({input: null});
   this.props.navigation.addListener('willBlur', () => BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton))
   return true
}

inside another function in same class component

this.props.navigation.addListener('willFocus', () => BackHandler.addEventListener('hardwareBackPress', this.handleBackButton))

enter image description here

CodePudding user response:

when you call BackHandler.exitApp(); app will close but it will remain in android’s recent tab.

BackHandler.exitApp();

Here, I will share React Native BackHandler example to use when the user presses the back button. when you want to exit the application when the user clicks on the back button you have to use hardwareBackPress EventListener, let’s understand with an example.

import React, { Component } from "react";
import { Text, View, StyleSheet, BackHandler, Alert } from "react-native";

class App extends Component {

  backAction = () => {
    Alert.alert("Hold on!", "Are you sure you want to go back?", [
      {
        text: "Cancel",
        onPress: () => null,
        style: "cancel"
      },
      { text: "YES", onPress: () => BackHandler.exitApp() }
    ]);
    return true;
  };

  componentDidMount() {
    this.backHandler = BackHandler.addEventListener(
      "hardwareBackPress",
      this.backAction
    );
  }

  componentWillUnmount() {
    this.backHandler.remove();
  }

  render() {
    return (
      <View style={styles.container}>
        <Text onPress = {this.backAction} style={styles.text}>Click Back button!</Text>
      </View>
    );
  }
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center"
  },
  text: {
    fontSize: 18,
    fontWeight: "bold"
  }
});

export default App;

CodePudding user response:

if you are trying to exit the app use

BackHandler.exitApp()

read the documntation

CodePudding user response:

import {BackHandler,Alert} from 'react-native';
const backAction = () => {
    Alert.alert('AppName', 'Are you sure you want to exit?', [
      {
        text: 'NO',
        onPress: () => null,
        style: 'cancel',
      },
      {text: 'YES', onPress: () => BackHandler.exitApp()},
    ]);
    return true;
  };

useEffect(() => {
    BackHandler.addEventListener('hardwareBackPress', backAction);
    return () => {
      BackHandler.removeEventListener('hardwareBackPress', backAction);
    };
  }, []);
  • Related