lil
lil

Reputation: 1

How to use Backhandler in React-native

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

There are four of button in the screen to go to each View.(in same class component)

Upvotes: 0

Views: 2353

Answers (3)

user17210172
user17210172

Reputation:

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

BackHandler.exitApp();

Here, I will share a react-native BackHandler api example. When you want to exit the application with clicking the back button, you should use hardwareBackPress EventListener, let’s make it clear 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;

Upvotes: 3

ViShU
ViShU

Reputation: 418

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);
    };
  }, []);

Upvotes: 0

Hamed
Hamed

Reputation: 427

if you are trying to exit the app use

BackHandler.exitApp()

read the documntation

Upvotes: 0

Related Questions