Hello Friends 👋,

Welcome To Infinitbility! ❤️

This tutorial help you to disable back button in react native application plus also how to do your stuff when user click on back button. Here I will share a common component example and you can use on any screen on React Native project.

Here, I’m going to create a common component for handle back press or also call back feature.

BackPressHandler.js

import React from 'react';
import {BackHandler} from 'react-native';

export default BackPressHandler = callback => {
    BackHandler.addEventListener('hardwareBackPress', () => {
      callback();
      return true;
    });
}

Using BackHandler and addEventListener we will handle the back press in android, let see how we use the BackPressHandler component on our react-native screen.

Suppose, we have ExampleScreen.js where we have to BackPressHandler component then first we have to import BackPressHandler component on our ExampleScreen.js and call BackPressHandler on componentDidMount function with our back press stuff task function in BackPressHandler component like below example.

ExampleScreen.js

import React, { Component } from 'react';
import { View, Text, Platform} from 'react-native';
import BackPressHandler from './BackPressHandler';

class ExampleScreen extends Component {

    constructor(props) {
        super(props);
      
        this.state  =   {
            message : 'Hi, ExampleScreen',
        }
    }

    componentDidMount() {
        if (Platform.OS == 'android') {
            BackPressHandler(this.BackStuff);
        }
    }

    BackStuff = () => {
        //   Wharever you want to do
    }

    render() {
        const { names } = this.state;
        return (
            <View>
                <Text>{this.state.message}</Text>
            </View>
        );
    }
}

export default ExampleScreen;

Write your back press task on BackStuff() function…

Thanks for Reading…