Skip to main content

Stack Navigator - Move Between Screens

In the previous section Hello React Navigation we defined a stack navigator with two routes Home and Details, but we didn’t know how to let the user go from Home to Details.

If it was a web browser, we could write something like this:

<a href="details.html">Go to Details</a>
<a
onClick={() => {
window.location.href = 'details.html'
}}
>
Go to Details
</a>

We'll do something like this, but instead of using the global window window.location we will use the navigation property that is passed to our screen components.

Go to new screen#

App.js
import * as React from 'react'
import { View, Button, Text } from 'react-native'
import { NavigationContainer } from '@react-navigation/native'
import { createStackNavigator } from '@react-navigation/stack'
const HomeScreen = ({ navigation }) => (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<Button title="Go to Details" onPress={() => navigation.navigate('Details')} />
</View>
)
const DetailsScreen = () => (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Details Screen</Text>
</View>
)
const Stack = createStackNavigator()
const App = () => (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Details" component={DetailsScreen} />
</Stack.Navigator>
</NavigationContainer>
)
export default App

Try this example on Snack

Let's deal with this:

  • navigation - the navigation property is passed to each screen component in the stack navigator.
  • navigate ('Details') - we call the navigate function with the name of the route we would like to navigate the user.
info

If we call navigation.navigate with a route name that we did not define in the navigator, it will throw an error in development assemblies and nothing will happen in production assemblies. In other words, we can only jump to routes that have been defined in our navigator - we cannot jump to an arbitrary component.

Payment#

Now you are on a stripped-down version of the site, after subscribing to Patreon, you will get full access to the training course, as well as access to our server's private channels in Discord.

Download our mobile application or get tested in our JavaScript telegram bot, and also subscribe to our news.

Become a Patron!

Sumerian school

Contributors ✨#

Thanks goes to these wonderful people (emoji key):


Dmitriy Vasilev

📖💲

Become a Patron!