Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call function every time the component becomes the active tab in react-native

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?

like image 579
Kavidu Aloka Kodikara Avatar asked Sep 06 '25 06:09

Kavidu Aloka Kodikara


1 Answers

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.

like image 91
SDushan Avatar answered Sep 07 '25 21:09

SDushan