How to use Backhandler (React-Native)?

Asked

Viewed 3,253 times

0

I started learning about React-Turn on a little while ago and created an application. In it I put a button to return from scene that works normally, but when I try to use the back button of the mobile the application is closed.

Description that I have to use the command Backhandler to make the button of the phone back to scene too, but so far I have not found an example of code that tells exactly which parts should be adapted to each code and which should be maintained

This is the code example I found:

return (
        componentDidMount() {
        BackHandler.addEventListener('backPress', () => {
            const { dispatch, nav } = this.props
            if (shouldCloseApp(nav)) 
                return false
            dispatch({ type: 'Back' })
                return true
        })
    }

componentWillUnmount() {
      BackHandler.removeEventListener('backPress')
    }

But when I tried to put to run gave the error "Unespected toekn" on the command line "componentDidMount(){".

What I have to do?

1 answer

1


I believe the error is in the location where you overwritten the componentWillMount() and componentWillUnmount functions()

The correct structure should be something like:

import React, { Component } from 'react';
import { View, BackHandler } from 'react-native';

class MyScreen extends Component {

  constructor(props){
    super(props);
  }

  componentDidMount() {
    BackHandler.addEventListener('backPress', () => {
      const { dispatch, nav } = this.props;
      if (shouldCloseApp(nav)) 
        return false;
      dispatch({ type: 'Back' });
      return true;
    });
  }

  componentWillUnmount() {
    BackHandler.removeEventListener('backPress')
  }

  render(){
    return(
      <View> {...} </View>
    )
  }
}
  • I put this way in all scenes but it appeared error "Can’t find variable: shouldCloseApp", how do I declare?

  • I don’t know what she’s talking about. I thought it was related to some part of her code. If you just want to return to the scene, just change everything that is inside the Listener’s Handler to this.props.Navigator.pop() (Checking if this.props.Navigator is different from null before.

  • I changed as suggested, now the application starts to come back from the scene but before finishing the process it closes. By chance you know what I should do?

  • Maybe you could give more details, this closure is simply close the application or is it giving some crash? I would need more information to help.

  • Does not show any error message, when I click the back button of the mobile phone the screen starts to return, but before loading the previous screen the application closes without leaving any message.

  • I recorded a video to show what’s happening: link

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.