How to detect when keyboard is opened or closed in React Native - react-native

How to detect if user close the keyboard in react native, I want to call a function when user closed the keyboard.
and if you can answer to detect keyboard is open too it will be appreciated, thanks.
I'm on the react native latest version 0.56

Thank you guys for your answers. Here is the hooks version if someone is interested:
const [isKeyboardVisible, setKeyboardVisible] = useState(false);
useEffect(() => {
const keyboardDidShowListener = Keyboard.addListener(
'keyboardDidShow',
() => {
setKeyboardVisible(true); // or some other action
}
);
const keyboardDidHideListener = Keyboard.addListener(
'keyboardDidHide',
() => {
setKeyboardVisible(false); // or some other action
}
);
return () => {
keyboardDidHideListener.remove();
keyboardDidShowListener.remove();
};
}, []);

1. You can use Keyboard class from facebook.
Here is a sample code.
import React, { Component } from 'react';
import { Keyboard, TextInput } from 'react-native';
class Example extends Component {
componentWillMount () {
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
}
componentWillUnmount () {
this.keyboardDidShowListener.remove();
this.keyboardDidHideListener.remove();
}
_keyboardDidShow () {
alert('Keyboard Shown');
}
_keyboardDidHide () {
alert('Keyboard Hidden');
}
render() {
return (
<TextInput
onSubmitEditing={Keyboard.dismiss}
/>
);
}
}
###2. You can use some other npm dependency also, like react-native-keyboard-listener.
Import the component into the file you want to use it:
import KeyboardListener from 'react-native-keyboard-listener';
Use the component directly in your code. The component won't render anything
<View>
<KeyboardListener
onWillShow={() => { this.setState({ keyboardOpen: true }); }}
onWillHide={() => { this.setState({ keyboardOpen: false }); }}
/>
</View>
To install this dependency run below command.
npm install --save react-native-keyboard-listener
Choose any you feel more convenient.

I wrapped this up in a hook:
import { useState, useEffect } from 'react';
import { Keyboard } from 'react-native';
export const useKeyboardVisible = () => {
const [isKeyboardVisible, setKeyboardVisible] = useState(false);
useEffect(() => {
const keyboardDidShowListener = Keyboard.addListener(
'keyboardDidShow',
() => {
setKeyboardVisible(true);
},
);
const keyboardDidHideListener = Keyboard.addListener(
'keyboardDidHide',
() => {
setKeyboardVisible(false);
},
);
return () => {
keyboardDidHideListener.remove();
keyboardDidShowListener.remove();
};
}, []);
return isKeyboardVisible;
};
The hook returns a boolean flag that can be used to apply logic conditionally or run any other effect needed.

Improved version of #Khemraj 's answer (which worked great for me) with bound methods to the instance in order to be able to update the component's state from the listener and re-render.
import React, { Component } from 'react';
import { Keyboard, TextInput } from 'react-native';
class Example extends Component {
state = {
keyboardState: 'closed'
}
componentWillMount () {
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
}
componentWillUnmount () {
this.keyboardDidShowListener.remove();
this.keyboardDidHideListener.remove();
}
_keyboardDidShow = () => {
this.setState({
keyboardState: 'opened'
});
}
_keyboardDidHide = () => {
this.setState({
keyboardState: 'closed'
});
}
render() {
return (
<TextInput
onSubmitEditing={Keyboard.dismiss}
/>
);
}
}

I came across the usekeyboard hook found in #react-native-community/hooks
E.g.
import { useKeyboard } from '#react-native-community/hooks'
const keyboard = useKeyboard()
console.log('keyboard isKeyboardShow: ', keyboard.keyboardShown)
console.log('keyboard keyboardHeight: ', keyboard.keyboardHeight)
Source: https://github.com/react-native-community/hooks/blob/master/src/useKeyboard.ts

I used a small remix to the great answer from #halbano that may be useful to consider depending on your situation
export default function useKeyboardOffsetHeight(): number {
const [keyBoardOffsetHeight, setKeyboardOffsetHeight] = useState(0);
useEffect(() => {
const keyboardWillShowListener = Keyboard.addListener(
"keyboardWillShow",
(e) => {
setKeyboardOffsetHeight(e.endCoordinates.height);
}
);
const keyboardWillHideListener = Keyboard.addListener(
"keyboardWillHide",
() => {
setKeyboardOffsetHeight(0);
}
);
return () => {
keyboardWillHideListener.remove();
keyboardWillShowListener.remove();
};
}, []);
return keyBoardOffsetHeight;
}
keyBoardOffsetHeight vs isKeyboardVisible
I used integer keyBoardOffsetHeight instead of boolean isKeyboardVisible . Since it's often useful to move some of your other components based on the keyboard size. The offset is either 0 (hidden) or Y > 0 pixels (it is shown). Then I can use that in styling like so:
const keyBoardOffsetHeight = useKeyboardOffsetHeight();
...
<View
style={{
bottom: keyBoardOffsetHeight,
}}
>
keyboardWillShow vs keyboardDidShow
Secondly, I use keyboardWillShow events so that I can anticipate the keyboard appearing and fire my UI changes earlier.
The keyboardDidShow event fires once the keyboard has already appeared.
I also used keyboardWillHide instead of keyboardDidHide based on the same reasoning.

MobX version:
import { observable } from 'mobx'
import { EmitterSubscription, Keyboard } from 'react-native'
class KeyboardStore {
#observable isKeyboardVisible = false
keyboardSubs: EmitterSubscription[] = []
subKeyboard() {
this.keyboardSubs = [
Keyboard.addListener('keyboardDidShow', () => this.isKeyboardVisible = true),
Keyboard.addListener('keyboardDidHide', () => this.isKeyboardVisible = false),
]
}
unsubKeyboard() {
this.keyboardSubs.forEach(sub => sub.remove())
this.keyboardSubs = []
}
}
and inside top level App component
useEffect(() => {
store.subKeyboard()
return () => {
store.unsubKeyboard()
}
}, [])
and check anywhere in your app with store.isKeyboardVisible.

All the thing already avalable in react-native Keyboard class
import React, { Component } from 'react';
import { Keyboard, TextInput } from 'react-native';
class Example extends Component {
componentDidMount() {
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
this.keyboardWillShowListener = Keyboard.addListener('keyboardWillShow', this._keyboardWillShow);
this.keyboardWillHideListener = Keyboard.addListener('keyboardWillHide', this._keyboardWillHide);
}
componentWillUnmount() {
this.keyboardDidShowListener.remove();
this.keyboardDidHideListener.remove();
this.keyboardWillShowListener.remove();
this.keyboardWillHideListener.remove();
}
_keyboardWillShow() {
console.log('Keyboard Showning')
}
_keyboardWillHide() {
console.log('Keyboard Heding')
}
_keyboardDidShow() {
alert('Keyboard Shown');
}
_keyboardDidHide() {
alert('Keyboard Hidden');
}
render() {
return (
<TextInput
onSubmitEditing={Keyboard.dismiss}
/>
);
}
}

Related

React navigation and loading component in react native

Hello I have a react component like which either display a list of items or opens another component which allowes me to select some value. Here is the code
import React, { PureComponent } from "react";
import { Text, View } from "react-native";
import { withNavigationFocus } from "react-navigation-is-focused-hoc";
import { NavigationActions } from "react-navigation";
import { connect } from "react-redux";
import ClassListing from '../../components/ClassListing/ClassListing';
import Actions from "../../state/Actions";
import { default as stackStyles } from "./styles";
import {
StyleCreator
} from "../../utils";
let styles = StyleCreator(stackStyles.IndexStyles)();
#withNavigationFocus
#connect(() => mapStateToProps, () => mapDispatchToProps)
export default class ClassList extends PureComponent {
static navigationOptions = ({ navigation }) => {
const { params } = navigation.state;
return {
header: null,
tabBarOnPress({ jumpToIndex, scene }) {
params.onTabFocus();
jumpToIndex(scene.index);
},
};
};
constructor(props) {
super(props);
this.state = {};
console.ignoredYellowBox = ["Warning: In next release", "FlatList"];
}
componentDidMount() {
console.log("componentDidMount");
this.props.navigation.setParams({
onTabFocus: this.handleTabFocus
});
}
componentDidUpdate() {
console.log("I am updated");
}
_handleNavigationBar = () => (
<View style={styles.headerContainer}>
<Text style={styles.headerLeftTitle}>Klasselister</Text>
</View>
);
handleTabFocus = () => {
this.props.resetClassList();
// setTimeout(() => {
// this._openChildSchoolSelector();
// },500);
};
_openChildSchoolSelector = () => {
if (
!this.props.childrenSelection.selectedDependant ||
!this.props.childrenSelection.selectedSchool
) {
console.log("navigate to child selector");
this.props.navigation.dispatch(
NavigationActions.navigate({
routeName: "ChildSchoolSelector",
})
);
}
};
render() {
return (
<View>
{this._handleNavigationBar()}
{this.props.classList &&
this.props.classList.classList &&
this.props.classList.classList.length > 0 ? (
<ClassListing list={this.props.classList.classList} />
) : (
null
// this._openChildSchoolSelector()
)}
</View>
);
}
}
const mapStateToProps = (state) => {
const { classList, childrenSelection } = state.appData;
console.log("[Classlist] mapStateToProps", classList);
console.log("[Classlist] mapStateToProps", childrenSelection);
return {
classList,
childrenSelection
};
};
const mapDispatchToProps = (dispatch) => ({
resetClassList: () => {
dispatch(Actions.resetClassList());
},
});
My issue is that when I come to this tab, I want to reset the list which came from server and then open the school selector again, which I am doing in handleTabFocus. But there I have to first call
this.props.resetClassList();
this._openChildSchoolSelector()
The issue is that this._openChildSchoolSelector() is called while this.props.resetClassList() hasn't fininshed.
this.props.resetClassList() works like this
it calls an action like this
static resetClassList() {
return {
type: ActionTypes.RESET_CLASS_LIST
};
}
which then cleans the classlist like this
case ActionTypes.RESET_CLASS_LIST:
return createDefaultState();
in ClassListReducer.js
and also in ChildrenSelectionRedcuer.js
case ActionTypes.RESET_CLASS_LIST:
return createDefaultState();
Any hints to solve this? My project uses very old React navigation v1
One thing which I did was to use this
componentWillReceiveProps(nextProps) {
console.log(this.props);
console.log(nextProps);
if (
nextProps.isFocused &&
nextProps.focusedRouteKey == "ClassList" &&
(!nextProps.childrenSelection.selectedDependant ||
!nextProps.childrenSelection.selectedSchool)
) {
console.log("componentWillReceiveProps");
this._openChildSchoolSelector();
}
if (
this.props.isFocused &&
this.props.focusedRouteKey === "ClassList" &&
nextProps.focusedRouteKey !== "ClassList"
) {
console.log("reset");
this.props.resetClassList();
}
}
But not sure if this is an elegant way of doing this

react native setInterval cannot read property apply

I am new in react native I am trying to render the count of unread notification for that I called my API in HOC it is working fine for initial few seconds but after that, I started to get the below error
func.apply is not a function
below is my code
import React, { Component } from "react";
import PropTypes from "prop-types";
import { Modal, View } from "react-native";
import { themes } from "./constants";
import { AsyncStorage } from "react-native";
export default (OriginalComponent, animationType) =>
class extends Component {
static propTypes = {
handleFail: PropTypes.func,
theme: PropTypes.string,
visible: PropTypes.bool
};
state = {
modalVisible: true
};
static getDerivedStateFromProps({ visible }) {
if (typeof visible === "undefined") {
setInterval(
AsyncStorage.getItem("loginJWT").then(result => {
if (result !== null) {
result = JSON.parse(result);
fetch(serverUrl + "/api/getUnreadNotificationsCount", {
method: "GET",
headers: {
Authorization: "Bearer " + result.data.jwt
}
})
.then(e => e.json())
.then(function(response) {
if (response.status === "1") {
if (response.msg > 0) {
AsyncStorage.setItem(
"unreadNotification",
JSON.stringify(response.msg)
);
} else {
AsyncStorage.setItem("unreadNotification", 0);
}
}
})
.catch(error => {
alert(error);
// console.error(error, "ERRRRRORRR");
});
} else {
AsyncStorage.setItem("unreadNotification", 0);
}
}),
5000
);
return null;
}
return { modalVisible: visible };
}
handleOpenModal = () => {
this.setState({ modalVisible: true });
};
handleCloseModal = () => {
const { handleFail } = this.props;
this.setState({ modalVisible: false }, handleFail);
};
render() {
const { modalVisible } = this.state;
const { theme } = this.props;
return (
<View>
<Modal
animationType={animationType ? animationType : "fade"}
transparent={true}
visible={modalVisible}
onRequestClose={this.handleCloseModal}
>
<View style={themes[theme] ? themes[theme] : themes.transparent}>
<OriginalComponent
handleCloseModal={this.handleCloseModal}
{...this.props}
/>
</View>
</Modal>
</View>
);
}
};
I have not used getDerivedStateFromProps but, according to the docs, it is called on initial component mount and before each render update.
Thus your code is creating a new interval timer on each update without clearing any of the earlier timers, which could be causing a race condition of some sort.
You may want to consider using the simpler alternatives listed in the docs, or at a minimum, insure that you cancel an interval before creating a new one.

How to pass the value of useState to BackHandler.addEventListener

I'm using React Hooks and when I create an event listener for android back press handler, the state inside the callback function handler is empty!
In class components it works fine!
'use strict';
import React, { useState, useEffect } from 'react';
import { BackHandler } from 'react-native';
import TextInput from '../../../../components/TextInput';
export default function Foo() {
const [comment, setComment] = useState('');
useEffect(() => {
const handler = BackHandler.addEventListener(
'hardwareBackPress',
handleValidateClose
);
return () => handler.remove();
}, []);
const handleValidateClose = () => {
/* Here is empty */
console.log(comment);
};
return <TextInput onChangeText={setComment} value={comment} />;
}
The value should be the useState changed
handleValidateClose should be on your dependency array.
You can use your function outside the useEffect but should use with useCallback.
const handleValidateClose = useCallback(() => {
console.log(comment);
return true;
}, [comment]);
useEffect(() => {
const handler = BackHandler.addEventListener(
'hardwareBackPress',
handleValidateClose,
);
return () => handler.remove();
}, [handleValidateClose]);
You can also move the definition to inside useEffect, and add a comment as a dependency.
useEffect(() => {
const handleValidateClose = () => {
console.log(comment);
return true;
};
const handler = BackHandler.addEventListener(
'hardwareBackPress',
handleValidateClose,
);
return () => handler.remove();
}, [comment]);
To clean things up, create a useBackHandler.
export default function useBackHandler(handler) {
useEffect(() => {
BackHandler.addEventListener('hardwareBackPress', handler);
return () => {
BackHandler.removeEventListener('hardwareBackPress', handler);
};
});
}
And use it like this:
const handleValidateClose = () => {
console.log(comment);
return true;
};
useBackHandler(handleValidateClose);
Please config your project to use the eslint-plugin-react-hooks. That's a common pitfalls that the plugin would help you with.

React native show a strange behavior. Can someone explain?

I'am creating a simple application with authentication. To change a state using redux with react-native-navigation (v1). For example, index.js
...
import { Navigation, } from 'react-native-navigation';
import { Provider, } from 'react-redux';
import store from './src/store';
import registerScreens from './src/screens';
registerScreens(store, Provider);
class App {
constructor () {
this.auth = false;
store.subscribe(this.onStoreUpdate.bind(this));
this.start();
}
onStoreUpdate () {
const state = store.getState();
if (this.auth != state.auth) {
this.auth = state.auth;
this.start();
}
}
start () {
switch (this.auth) {
case false:
Navigation.startTabBasedApp({
tabs: [{
screen: 'navigation.AuthScreen',
}, {
screen: 'navigation.RegisterScreen',
},],
});
break;
case true:
Navigation.startSingleScreenApp({
screen: {
screen: 'navigation.MainScreen',
},
});
break;
}
}
}
const application = new App();
Store is listening an update and change an application layout if need.
AuthScreen show a simple ActivityIndicator, when server request is perform. For example, auth.js
...
import { bindActionCreators, } from 'redux';
import { connect, } from 'react-redux';
import * as actions from './../actions';
...
class AuthScreen extends Component {
constructor (props) {
super(props);
this.state = {
loading: false,
...
};
this.handlePressEnter = this.handlePressEnter.bind(this);
}
handlePressEnter () {
...
this.loadingState(true);
jsonFetch(url, {
method: 'POST',
body: JSON.stringify({...}),
}).then((value) => {
this.loadingState();
this.props.actions.auth(true);
}).catch((errors) => {
this.loadingState();
console.log('Error while auth', errors);
});
}
...
loadingState (state = false) {
this.setState({
loading: state,
});
}
render () {
return (<View>
...
<Modal visible={this.state.loading} transparent={true} animationType="none" onRequestClose={() => {}}>
<View>
<ActivityIndicator size="large" animating={this.state.loading} />
</View>
</Modal>
</View>);
}
}
function mapStateToProps (state, ownProps) {
return {};
}
function mapDispatchToProps (dispatch) {
return {
actions: bindActionCreators(actions, dispatch),
};
}
export default connect(mapStateToProps, mapDispatchToProps) (AuthScreen);
I'am starting application with iOS simulator and try to authenticate. It show me activity indicator, then indicator disappear, but layout does not change. And strange behavior, if I comment this.loadingState(true); and this.loadingState(); in auth.js layout changes with success.
Can someone explain to me, why layout does not change from auth to main when activity indicator using?
I think that you can use dispatch props for loading.
For example When you call this.props.actions.auth(true);
You can return loading reducers.
handlePressEnter () {
...
dispatch({ type:'loading', loading: true });
jsonFetch(url, {
method: 'POST',
body: JSON.stringify({...}),
}).then((value) => {
dispatch({ type:'loading', loading: false });
this.props.actions.auth(true);
}).catch((errors) => {
this.loadingState();
console.log('Error while auth', errors);
});
}
And than you can use
<ActivityIndicator size="large" animating={this.props.loading} />
But dont forget the reducers return

React Native - Device back button handling

I want to check if there are more than one screens are on stack when device back button is hit. If yes, I want to show previous screen and if no, I want to exit app.
I have checked number of examples but those use BackAndroid and Navigator. But both of them are deprecated. BackHandler is replacement for BackAndroid. And I can show previous screen by using props.navigation.goBack(null).
But I am unable to find code for finding screen count in stack. I don't want to use deprecated Navigator!
This example will show you back navigation which is expected generally in most of the flows. You will have to add following code to every screen depending on expected behavior. There are 2 cases:
1. If there are more than 1 screen on stack, device back button will show previous screen.
2. If there is only 1 screen on stack, device back button will exit app.
Case 1: Show previous screen
import { BackHandler } from 'react-native';
constructor(props) {
super(props)
this.handleBackButtonClick = this.handleBackButtonClick.bind(this);
}
componentWillMount() {
BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);
}
handleBackButtonClick() {
this.props.navigation.goBack(null);
return true;
}
Important: Don't forget to bind method in constructor and to remove listener in componentWillUnmount.
Case 2: Exit App
In this case, no need to handle anything on that screen where you want to exit app.
Important: This should be only screen on stack.
In functional component:
import { BackHandler } from "react-native";
function handleBackButtonClick() {
navigation.goBack();
return true;
}
useEffect(() => {
BackHandler.addEventListener("hardwareBackPress", handleBackButtonClick);
return () => {
BackHandler.removeEventListener("hardwareBackPress", handleBackButtonClick);
};
}, []);
import { BackHandler } from 'react-native';
constructor() {
super();
this.handleBackButtonClick = this.handleBackButtonClick.bind(this);
}
componentWillMount() {
BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);
}
handleBackButtonClick() {
//this.props.navigation.goBack(null);
BackHandler.exitApp();
return true;
}
handleBackButtonClick() {
return true; // when back button don't need to go back
}
In Functional Component
import { BackHandler } from 'react-native';
function handleBackButtonClick() {
navigation.goBack();
return true;
}
useEffect(() => {
BackHandler.addEventListener('hardwareBackPress', handleBackButtonClick);
return () => {
BackHandler.removeEventListener('hardwareBackPress', handleBackButtonClick);
};
}, []);
In a case where there are more than one screens stacked in the stack, the default back button behavior in react-native is to navigate back to the previous screen in the stack. Handling the device back button press when having only one screen to exit the app requires a custom setting. Yet this can be achieved without having to add back handling code to each and every screen by modifying the getStateForAction method of the particular StackNavigator's router.
Suppose you have the following StackNavigator used in the application
const ScreenStack = StackNavigator(
{
'Screen1': {
screen: Screen1
},
'Screen2': {
screen: Screen2
},
},
{
initialRouteName: 'Screen1'
}
);
The getStateForAction method of the stack navigator's router can be modified as follows to achieve the expected back behavior.
const defaultStackGetStateForAction =
ScreenStack.router.getStateForAction;
ScreenStack.router.getStateForAction = (action, state) => {
if(state.index === 0 && action.type === NavigationActions.BACK){
BackHandler.exitApp();
return null;
}
return defaultStackGetStateForAction(action, state);
};
the state.index becomes 0 only when there is one screen in the stack.
Here is how I implemented successfully using certain condition:
componentWillMount() {
BackHandler.addEventListener(
'hardwareBackPress',
this.handleBackButtonClick,
);
}
componentWillUnmount() {
BackHandler.removeEventListener(
'hardwareBackPress',
this.handleBackButtonClick,
);
}
handleBackButtonClick = () => {
//some condition
if (this.state.isSearchBarActive) {
this.setState({
isSearchBarActive: false,
});
this.props.navigation.goBack(null);
return true;
}
return false;
};
React Native Hooks has a nice useBackHandler hook which simplifies the process of setting up event listeners for Android back button.
import { useBackHandler } from '#react-native-community/hooks'
useBackHandler(() => {
if (shouldBeHandledHere) {
// handle it
return true
}
// let the default thing happen
return false
})
try this
react navigation
componentDidMount() {
BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
}
handleBackButton = () => {
const pushAction = StackActions.push({
routeName: 'DefaultSelections',
});
this.props.navigation.dispatch(pushAction);
}
current screen is "DefaultSelections" , on back button press, would be shifted on to the same and hence back button disabled work around, as disabling back button by
return true
for backButton ( as suggested by the official docs ) disables back button on all screens ; not wanted
an utility function could be very helpful:
backPressHandler.js
import React from 'react';
import {BackHandler} from 'react-native';
const onBackPress = (callback) => {
BackHandler.addEventListener('hardwareBackPress', callback);
return () => {
BackHandler.removeEventListener('hardwareBackPress', callback);
};
};
export {onBackPress};
now in my screen:
myScreen.js
import {onBackPress} from '../utils/backPressHandler';
function handleBackPress() {
navigation.goBack();
return true;
}
useEffect(() => {
onBackPress(handleBackPress);
}, []);
I am on v0.46.0 of react-native and had the same issue. I tracked the issue down to this file in the react-native code base
https://github.com/facebook/react-native/blob/master/Libraries/Utilities/BackHandler.android.js#L25
When running with the chrome debugger turned off the line
var subscriptions = Array.from(_backPressSubscriptions.values()).reverse()
always returns an empty array for subscriptions which in turn causes the invokeDefault variable to stay true and the .exitApp() function to be called.
After more investigation, I think the issue was discovered and discussed in the following PR #15182.
Even after copy/pasting the PR change in an older version of RN it did not work most likely caused by the issue described in the PR.
After some very slight modifications I got it working by changing to
RCTDeviceEventEmitter.addListener(DEVICE_BACK_EVENT, function() {
var invokeDefault = true;
var subscriptions = []
_backPressSubscriptions.forEach(sub => subscriptions.push(sub))
for (var i = 0; i < subscriptions.reverse().length; ++i) {
if (subscriptions[i]()) {
invokeDefault = false;
break;
}
}
if (invokeDefault) {
BackHandler.exitApp();
}
});
Simply using a .forEach which was the original implementation on the PR before the amended Array.from syntax works throughout.
So you could fork react-native and use a modified version, submit a PR though I imagine that will take a little while to be approved and merged upstream, or you can do something similar to what I did which was to override the RCTDeviceEventEmitter.addListener(...) for the hardwareBackPress event.
// other imports
import { BackHandler, DeviceEventEmitter } from 'react-native'
class MyApp extends Component {
constructor(props) {
super(props)
this.backPressSubscriptions = new Set()
}
componentDidMount = () => {
DeviceEventEmitter.removeAllListeners('hardwareBackPress')
DeviceEventEmitter.addListener('hardwareBackPress', () => {
let invokeDefault = true
const subscriptions = []
this.backPressSubscriptions.forEach(sub => subscriptions.push(sub))
for (let i = 0; i < subscriptions.reverse().length; i += 1) {
if (subscriptions[i]()) {
invokeDefault = false
break
}
}
if (invokeDefault) {
BackHandler.exitApp()
}
})
this.backPressSubscriptions.add(this.handleHardwareBack)
}
componentWillUnmount = () => {
DeviceEventEmitter.removeAllListeners('hardwareBackPress')
this.backPressSubscriptions.clear()
}
handleHardwareBack = () => { /* do your thing */ }
render() { return <YourApp /> }
}
constructor(props){
super(props)
this.onBackPress = this.onBackPress.bind(this);
}
componentWillMount() {
BackHandler.addEventListener('hardwareBackPress', this.onBackPress);
}
componentWillUnmount(){
BackHandler.removeEventListener('hardwareBackPress', this.onBackPress);
}
onBackPress(){
const {dispatch, nav} = this.props;
if (nav.index < 0) {
return false;
}
dispatch(NavigationActions.back());
return true;
}
render(){
const {dispatch, nav} = this.props;
return(
<DrawerRouter
navigation= {
addNavigationHelpers({
dispatch,
state: nav,
addListener,
})
}
/>
);
}
If you use react-navigation, the other answers did not work for me but this did:
const handleGoBack = useCallback(() => {
// custom logic here
return true; // Returning true from onBackPress denotes that we have handled the event
}, [navigation]);
useFocusEffect(
React.useCallback(() => {
BackHandler.addEventListener('hardwareBackPress', handleGoBack);
return () =>
BackHandler.removeEventListener('hardwareBackPress', handleGoBack);
}, [handleGoBack]),
Here is the link to the documentation
useFocusEffect(
React.useCallback(() => {
const onBackPress = () => {
navigation.navigate('Journal');
return true;
};
BackHandler.addEventListener('hardwareBackPress', onBackPress);
return () => {
BackHandler.removeEventListener('hardwareBackPress', onBackPress);
};
}, []),
);
`
import { useFocusEffect} from '#react-navigation/native';
export default function App(props: any) {
function handleBackButton() {
navigation.goBack();
return true;
}
useFocusEffect(
React.useCallback(() => {
BackHandler.addEventListener("hardwareBackPress", handleBackButton);
return () => {
console.log("I am removed from stack")
BackHandler.removeEventListener("hardwareBackPress", handleBackButton);
};
}, [])
);
}
I used flux for navigation.
const RouterComp = () => {
let backLoginScene=false;
return (
<Router
backAndroidHandler={() => {
const back_button_prohibited = ['login','userInfo','dashboard'];
if (back_button_prohibited.includes(Actions.currentScene) ) {
if (backLoginScene == false) {
ToastAndroid.show("Click back again to exit.", ToastAndroid.SHORT);
backLoginScene = !backLoginScene;
setTimeout(() => {
backLoginScene = false;
}, 2000);
return true;
} else {
backLoginScene = false;
BackHandler.exitApp();
}
return false;
}}}>
<Scene key='root' hideNavBar>
<Scene key='guest' hideNavBar >
<Scene key='login' component={Login} ></Scene>
<Scene key='userInfo' component={UserInfo}></Scene>
</Scene>
<Scene key='user' hideNavBar>
<Scene key='dashboard' component={Dashboard} title='Dashboard' initial />
<Scene key='newAd' component={NewAd} title='New Ad' />
</Scene>
</Scene>
</Router>
)
}
export default RouterComp;