Search code examples
react-nativereact-navigationreact-native-tabnavigator

How do I programatically go from one tab to another tab in react native tab navigator?


import * as React from 'react';
import { Text, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';

function HomeScreen() {
  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>Home!</Text>
    </View>
  );
}

function SettingsScreen() {
  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>
  );
}

How do I programatically go from one tab to another tab in react native tab navigator? For example how do I go from "Home" tab screen to the "Settings" tab screen described above?


Solution

  • You can use the navigation prop which gets passed down to each tab. This is a object with a navigate method where you can provide the name of the screen you want to navigate to.

    function HomeScreen({ navigation }) {
      return (
        <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
          <Pressable onPress={() => navigation.navigate("Settings")}>
            <Text>Home!</Text>
          </Pressable>
        </View>
      );
    }