I want to trig a function, each time the component becomes active tab in bottom navigation react-native. Can somebody give me a solution for this?
Use focus
in Navigation events as below
componentDidMount() {
this.focusListener = this.props.navigation.addListener('focus',
() => alert('Screen focused'))
}
Make sure to remove the listener
componentWillUnmount() {
this.focusListener.remove();
}
For extra information check below example
import React, { Component } from "react";
import { Text, View } from "react-native";
import { NavigationContainer } from "@react-navigation/native";
import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
class HomeScreen extends Component {
componentDidMount() {
this.focusListener = this.props.navigation.addListener("focus", () =>
alert("Screen home")
);
}
componentWillUnmount() {
this.focusListener.remove();
}
render() {
return (
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
<Text>Home</Text>
</View>
);
}
}
class SettingsScreen extends Component {
render() {
return (
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
<Text>Settings</Text>
</View>
);
}
}
const Tab = createBottomTabNavigator();
export default function App() {
return (
<NavigationContainer>
<Tab.Navigator>
<Tab.Screen name="Home" component={HomeScreen} />
<Tab.Screen name="Settings" component={SettingsScreen} />
</Tab.Navigator>
</NavigationContainer>
);
}
Hope this helps you. Feel free for doubts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With