CodeBlanks Logo Icon CodeBlanks

Summary - Navigation

Combine Stack, navigate and params to write a two-screen app.

Summary - Navigation

In this group you learned the fundamentals of React Navigation. NavigationContainer is the root wrapper; you create a Stack with createNativeStackNavigator. Inside Stack.Navigator you place Stack.Screen components.

For transitions you use navigation.navigate('ScreenName', params). In the target screen you read data from route.params. To go back you call navigation.goBack(). Now let us combine all of this into a mini app.

Practice Your turn: navigate with params

Add a Button in HomeScreen. When pressed it should call navigation.navigate('Details', { itemNo: 7 }).

Starter code

App.js
function HomeScreen({ navigation }) {
  return (
    <View>
      <Text>Home</Text>
      {/* button to navigate with params */}
    </View>
  );
}

Sample solution

App.js
function HomeScreen({ navigation }) {
  return (
    <View>
      <Text>Home</Text>
      <Button
        title="Item 7"
        onPress={() => navigation.navigate('Details', { itemNo: 7 })}
      />
    </View>
  );
}

Practice Your turn: add a back button to Details

Have the DetailsScreen component receive route and navigation props. Destructure itemNo from route.params. Display it in a Text and add a Button that calls navigation.goBack().

Starter code

App.js
function DetailsScreen({ route, navigation }) {
  // get itemNo from params
  return (
    <View>
      {/* show itemNo and add a back button */}
    </View>
  );
}

Sample solution

App.js
function DetailsScreen({ route, navigation }) {
  const { itemNo } = route.params;
  return (
    <View>
      <Text>Item no: {itemNo}</Text>
      <Button title="Back" onPress={() => navigation.goBack()} />
    </View>
  );
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is the correct syntax to pass itemNo to Details?

  • navigate('Details', [7])
  • navigate('Details', 'itemNo')
  • navigate('Details', itemNo: 7)
  • navigate('Details', { itemNo: 7 }) Correct answer

Explanation: params are passed as an object { itemNo: 7 }.

2 Match: concept and usage

Term Meaning
NavigationContainer root wrapper
navigate screen opening
goBack going back

All lessons in Beginner