react-nativenavigationreact-navigation-bottom-tab

How to use onPress() with Bottom Tabs Navigator in React Native?


I am using Bottom Tabs Navigator in my app to navigate between screens. My problem is that on my welcome screen I have added two buttons (not bottom tabs) that I want to navigate to the Home screen and an Instructions screen using an onPress() function for each button. Will this work with Bottom Tabs Navigation or do I need to create a Stack Navigator? My thought was that I could use the navigation prop to navigate to the Home and Instructions screens but this is not working. The tabs themselves are working fine but I don't know how to incorporate the setup with the buttons I've created. Here's how I've tried to navigate to the Home screen.

const GetStartedButton = ({navigation}) => {    
  return (
    <View>
      <Pressable
        style={style.buttonContainer}
        onPress={() => navigation.navigate('Home')}>
        <Text>
          Get Started
        </Text>
      </Pressable>
    </View>
  );
};

export default GetStartedButton;

Tab Navigation:

const Tab = createBottomTabNavigator();
const MainNavigation = () => {
  return (
    <Tab.Navigator>
      <Tab.Screen
        name="Home"
        component={Welcome}
        options={{
          headerShown: false,
          tabBarIcon: ({size, color}) => <HouseIcon />,
          tabBarInactiveBackgroundColor: '#F1F5F8',
        }}
      />
    </Tab.Navigator>
  );
};

export default MainNavigation;

Welcome page where button is:

import {View, Text} from 'react-native';
import React from 'react';
import GetStartedButton from './GetStartedButton';
import Background from '../../components/Backgrounds/Background';
import lightGlobalStyles from '../../assets/globalStyles/lightGlobalStyles';
import themes from '../../assets/globalStyles/themes';
import {useTheme} from '../../ThemeContext';

import style from './style';
import HowToUse from './HowToUse';

const Welcome = () => {
  const theme = useTheme();
  return (
    <View style={lightGlobalStyles.affirmationContainer}>
      <View style={style.pressablesContainer}>
        <HowToUse />
        <GetStartedButton />
      </View>
      <Background />
    </View>
  );
};

export default Welcome;

Solution

  • Navigation object is undefined in GetStartedButton component. Either pass it to the component or use useNavigation hook to access it. Something like this:

    <GetStartedButton navigation={navigation}/>
    
    const GetStartedButton = () => {    
      const navigation = useNavigation();
      return (
        <View>
          <Pressable
            onPress={() => navigation.navigate('Home')}>
            <Text>
              Get Started
            </Text>
          </Pressable>
        </View>
      );
    };