Stack Navigator
Stack Navigator used for transition between screens.When you navigate to new screen,a new screen is placed on top of stack and when you navigate back the screen is removed and render previous screen
To use this navigator, install the necessary react native package by running following command
npm install @react-navigation/stack
Example:
- First Create component folder in src directory.Then we create Home.js and index.js files in HomeScreen folder
import React from 'react';
import {Button, Text, View} from 'react-native';
const HomeScreen = ({navigation}) => {
return (
<View>
<Text>Home screen</Text>
<Button
title="Go to Profile"
onPress={() => navigation.navigate('Profile')}
/>
</View>
);
};
export default HomeScreen;
Also create index.js file in same folder
import HomeScreen from './HomeScreen';
export {HomeScreen};
- Next create ProfileScreen folder with profile.js and index.js files
import React from 'react';
import {Button, Text, View} from 'react-native';
const ProfileScreen = ({navigation}) => {
return (
<View>
<Text> Profile Screen </Text>
<Button title="Go Back" onPress={() => navigation.goBack()} />
</View>
);
};
export default ProfileScreen;
import ProfileScreen from './ProfileScreen';
export {ProfileScreen};
- Let’s also make some changes to App.js
import * as React from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {createNativeStackNavigator} from '@react-navigation/native-stack';
import {HomeScreen} from './src/screens/HomeScreen';
import {ProfileScreen} from './src/screens/ProfileScreen';
import {AppConfig} from './src/configs';
const Stack = createNativeStackNavigator();
const MyStack = () => {
return (
<Stack.Navigator>
<Stack.Screen
name="Home"
component={HomeScreen}
options={{title: 'Welcome'}}
/>
<Stack.Screen name="Profile" component={ProfileScreen} />
</Stack.Navigator>
);
};
const App = () => {
return (
<NavigationContainer>
<MyStack />
</NavigationContainer>
);
}
export default App;
Here, we have executed the createNativeStackNavigator function and stored its instance into the Stack variable.
We can now navigate between the Home and Profile screens using the buttons provided.Using following button we can navigate Home screen to profile screen
<Button
title="Go to Profile"
onPress={() => navigation.navigate('Profile')}
/>
Create your screen navigation in the app.js component by placing the Home and Profile screens within the Stack.