Reputation: 7378
I'm adding updates to a React Native app that uses class components, and want to have a function triggered every time the user opens the app. For example, if they minimize and then reopen it. I know you can use AppState
if the app uses function components, but is there any way to achieve this with class components?
Upvotes: 0
Views: 1836
Reputation: 52387
You can listen for an app state change with class components:
import React, { Component } from "react";
import { AppState, StyleSheet, Text, View } 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 (
<View style={styles.container}>
<Text>Current state is: {this.state.appState}</Text>
</View>
);
}
}
Source: https://reactnative.dev/docs/appstate (click on Class Component
) above the code sample to switch from the default Function Component
code.
Upvotes: 3