Monday, June 3, 2024
118
rated 0 times [  124] [ 6]  / answers: 1 / hits: 59949  / 7 Years ago, tue, october 10, 2017, 12:00:00

Is it possible to know if a RN app has gone to background? Any callback or trigger?



If I listen to componentDidUnmount or componentWillUnmount of the screen I'm on, it will only be fired if I go back/forth to another screen


More From » react-native

 Answers
18

You can listen to the appState event.
From https://facebook.github.io/react-native/docs/appstate.html:



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>
);
}

}


By the way, this will always say 'Current state is: active', because that is the only state in which the app will be visible for the user.


[#56268] Saturday, October 7, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
krystadesiraeo

Total Points: 493
Total Questions: 93
Total Answers: 100

Location: San Marino
Member since Thu, Jun 30, 2022
2 Years ago
;