React Native: Remove goBack() function from Android’s physical button?

Asked

Viewed 948 times

1

I need to remove the Back Screen Action from the physical button of Android at any given time. Basically, I have a method that shows my Searchbar, while the Searchbar is visible, I need the action of returning screens to be disabled, and in its place, be enabled another method that I have that hides the Searchbar. After hiding it, I need to activate the function of back screens again. I am trying the following:

// oculta o header, exibe o searchbar
hideHeader () {

    /* código.... */

    /* Aqui tento remover a função de voltar tela e adicionar a função de 
    ocultar o SearchBar, no botão físico */
    BackHandler.addEventListener('hardwareBackPress', this.backButtonClick);
    BackHandler.addEventListener('hardwareBackPress', this.hideSearchBar);
}

// oculta SearchBar,  mostra header
hideSearchBar () {

    /* código.... */

    /* Aqui, removo a função que adicionei para desativar o this.props.navigation.goBack() */
    BackHandler.removeEventListener('hardwareBackPress', this.backButtonClick)
}

// adiciona ou remove a função this.props.navigation.goBack()
backButtonClick(){
    if(this.props.navigation && this.props.navigation.goBack){
        this.props.navigation.goBack(null);
        return true;
    }
    return false;
}

I can open Searchbar normally, the problem is when I press the Android button "Back", since Searchbar is visible, it should only hide it. But in addition to hiding, it goes back to the previous screen.

If anyone can help, I’d be grateful!

1 answer

1

When the event of hardwareBackPress is fired or you return to the previous screen of your Stack or you cancel through conditions. For example, create a variable that will indicate whether the search field is open or closed. So when you press the Voltar from the phone he will make the check and decide what action will have to do.

state={
    searchOpen: false
}

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

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

// adiciona ou remove a função this.props.navigation.goBack()
backButtonClick() {
    if (this.state.searchOpen) {

        this.setState({ searchOpen: false });

        return false;
    }

    this.props.navigation.goBack(null);

    return true;
}

Browser other questions tagged

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