Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-native android back button in react-navigation

Well, I have a react-native app with multiple screen, each screen having a top bar where a back button is situated, it's main behavior is that the app returns to the main screen when this button is pressed. What I want to do is to copy this behavior to the hardware back button (now by pressing on hardware back button the app closes), how can I do this?

UPDATE:

I'm using react-navigation and redux

like image 328
Eugen-Andrei Coliban Avatar asked Jun 08 '18 12:06

Eugen-Andrei Coliban


People also ask

How do I add a back button in 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.

Which callback of modal is fired when hardware back button is pressed?

The Backhandler API detects hardware button presses for back navigation, lets you register event listeners for the system's back action, and lets you control how your application responds. It is Android-only.

What is Auth in React Native?

Authentication allows us to secure our apps, or limit access for non-user members. Authentication can also be used, for example, to limit access to a paid service or specific service. That's just one example of how authentication can be in your app. Today we will add authentication to a React Native app using Firebase.


2 Answers

You can do it by below example

import { BackHandler } from 'react-native';

class App extends Component {
  constructor(props){
    super(props);
    this.backButtonClick = this.backButtonClick.bind(this);
  }

  componentDidMount() {
    BackHandler.addEventListener('hardwareBackPress', this.backButtonClick);
  }

  componentWillUnmount(){
    BackHandler.removeEventListener('hardwareBackPress', this.backButtonClick);
  }

  backButtonClick(){
    if(this.props.navigation && this.props.navigation.goBack){
      this.props.navigation.goBack(null);
      return true;
    }
    return false;
  }
}
like image 74
Javascript Hupp Technologies Avatar answered Oct 18 '22 19:10

Javascript Hupp Technologies


You can:

  1. import the BackHandler from "react-native"
  2. Add in the componentDidMount (componentWillMount deprecated) BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
  3. Implement handleBackButton like this handleBackButton(){ this.props.navigation.popToTop(); return true; }

popToTop goes back to the first screen in the stack.

If you are using react-navigation with Redux you should implement the popToTop as an action to dispatch.

like image 26
Paolo Dell'Aguzzo Avatar answered Oct 18 '22 19:10

Paolo Dell'Aguzzo