Last active
December 14, 2021 11:46
-
-
Save joelash/06dcd13dc742382a4749a1d12ff0e9d8 to your computer and use it in GitHub Desktop.
React Native Detect Backgrounding/Foregrounding
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import { | |
AppState, | |
} from 'react-native'; | |
import Expo from 'expo'; | |
class App extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
appState: AppState.currentState, | |
}; | |
} | |
componentDidMount() { | |
AppState.addEventListener('change', this._handleAppStateChange); | |
} | |
componentWillUnmount() { | |
AppState.removeEventListener('change', this._handleAppStateChange); | |
} | |
_backgroundState(state) { | |
return state.match(/inactive|background/); | |
} | |
_handleAppStateChange = (nextAppState) => { | |
if (this._backgroundState(nextAppState)) { | |
console.log("App is going background"); | |
} else if (this._backgroundState(this.state.appState) && (nextAppState === 'active')) { | |
console.log("App is coming to foreground"); | |
} | |
this.setState({appState: nextAppState}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you