I have looked everywhere and cannot find an answer to this. How can I detect when a user is trying to close my React Native app (as in the process is running, and they manua
As a simple method , we can use componentWillUnmount() inside the root component for detect the app is closed. Because Root component Unmount only when app is closed. :)
Looks like you can detect the previous state and compare it to the next state. You can't detect that the app is closing vs going into the background, from what I can find online, but you can detect if it was inactive
(closed), or in the background
.
import React, {Component} from 'react'
import {AppState, Text} from 'react-native'
class AppStateExample extends Component {
state = {
appState: AppState.currentState
}
componentDidMount() {
AppState.addEventListener('change', this._handleAppStateChange);
}
componentWillUnmount() {
AppState.removeEventListener('change', this._handleAppStateChange);
}
_handleAppStateChange = (nextAppState) => {
if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
console.log('App has come to the foreground!')
}
this.setState({appState: nextAppState});
}
render() {
return (
<Text>Current state is: {this.state.appState}</Text>
);
}
}