Home > Software engineering >  React Navigation Bottom Tabs Navigator plus Modal Screen
React Navigation Bottom Tabs Navigator plus Modal Screen

Time:12-06

I have the following code to create a Tab using React Native Navigation v6.x:

import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';

const Tab = createBottomTabNavigator();

function MyTabs() {
  return (
    <Tab.Navigator>
      <Tab.Screen name="Home" component={HomeScreen} />
      <Tab.Screen name="Settings" component={SettingsScreen} />
    </Tab.Navigator>
  );
}

The HomeScreen has a button which should call a Modal Screen.

My question is: How would I add this modal screen in my Navigator to call it from HomeScreen and how would be this call code?

Thanks!

CodePudding user response:

You don't need to include the modal in the navigator to open it from the homepage.

You could do something like this:

const HomeScreen = () => {
  const [modalVisible, setModalVisible] = useState(false);

  function _myModal() {

    return(
      <Modal
        animationType="slide"
        visible={modalVisible}
        onRequestClose={() => {setModalVisible(false)}}
      >
        <Text>Hello, I am a modal!</Text>
      </Modal>
    )
  }

  // your code
  return (
    <View>
      {/*your code*/}
      <Pressable
        onPress={() => setModalVisible(true)}
      >
        <Text>Show Modal</Text>
      </Pressable>
      {_myModal()}
    </View>
  );
};

The React-Native documentation has an example for class component as well in case you're working with these, and more info that should help you as well.

CodePudding user response:

If you want to open modal screen from your home page then you should create a home screen stack navigator and add two screen in that stack(home and modal screens), and then navigate to that modal by pressing button.

Tab Navigator(RootNavigation MyTabs)

...
function MyTabs() {
  return (
    <Tab.Navigator>
      <Tab.Screen name="Home" component={HomeStack} />
      <Tab.Screen name="Settings" component={SettingsScreen} />
    </Tab.Navigator>
  );
}

Stack Navigator(HomeStack)

cosnt Stack = createStackNavigator();

function HomeStack() {
  return (
    <Stack.Navigator>
      <Stack.Screen name="HomeScreen" component={HomeScreen} />
      <Stack.Screen name="ModalScreen" component={ModalScreen}
         options={{ presentation: 'modal' }} />
    </Stack.Navigator>
  );
}

HomeScreen

export default function HomeScreen({navigation}) {
   return (
      <View>
          <TouchableOpacity onPress={() => navigation.navigate('ModalScreen'}>
              <Text>Open ModalScreen</Text>
          </TouchableOpacity>
      </View>
   )
}
  • Related