React Native BackHandler Component Example Tutorial

React Native

Nicesnippets

1215

08-08-2020


React Native BackHandler Component Example Tutorial

Hi Guys,

In this blog, I will explain you how to create backhandler component in react native. You can easily create backhandler component in react native. First i will import namespace BackHandler


, after I will make backhandler component using method in react native.

Here, I will give you full example for simply display backhandler component using react native as bellow.

Step 1 - Create project

In the first step Run the following command for create project.

expo init BackhandlerComponent

Step 2 - App.js

In this step, You will open App.js file and put the code.

import React, { Component } from "react";

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

class App extends Component {

backAction = () => {

Alert.alert("Wait!", "Are you sure 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 style={styles.text}>Please Click On Back Button</Text>

</View>

);

}

};

const styles = StyleSheet.create({

container: {

flex: 1,

alignItems: "center",

justifyContent: "center"

},

text: {

fontSize: 22,

fontWeight: "bold",

color : "cadetblue"

}

});

export default App;

Step 3 - Run project

In the last step run your project using bellow command.

npm start

Output

It will help you...