CodeBlanks Logo Icon CodeBlanks

Back button

Learn the back button and goBack.

The goBack function

To return from a screen to the previous one you call navigation.goBack(). This pops the top screen from the stack and shows the one below. In a stack navigator a back button usually appears automatically in the header.

Sometimes you want to place your own back button. You add a Button and call navigation.goBack() in its onPress handler. goBack takes no parameter; it always pops the top screen. If there is no screen to go back to, it does nothing.

Android hardware back button

Android devices have a physical or software back button. The stack navigator intercepts this button automatically and applies the goBack behavior; you do not need extra code. When the user presses back the previous screen appears.

If you need custom behavior on back (for example showing a warning about unsaved data), you can customize the button with useFocusEffect or BackHandler. At the beginner level the default behavior is sufficient for most cases.

Practice Your turn: add a back button

Add a Button to the DetailsScreen component. When pressed it should call navigation.goBack(). Receive the navigation prop from the component parameters.

Starter code

App.js
function DetailsScreen({ navigation }) {
  return (
    <View>
      <Text>Details screen</Text>
      {/* add a back button */}
    </View>
  );
}

Sample solution

App.js
function DetailsScreen({ navigation }) {
  return (
    <View>
      <Text>Details screen</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 Match: function and effect

Term Meaning
goBack pops top screen
navigate pushes new screen
popToTop returns to start

2 What does navigation.goBack() do?

App.js
navigation.goBack()
  • Restarts the app
  • Pushes a new screen
  • Pops the top screen from the stack Correct answer
  • Deletes all params

Explanation: goBack pops the top screen and returns to the previous one.

3 Fill in the blank: go back

Question
navigation.____();
Answer
navigation.goBack();

Explanation: goBack returns you to the previous screen.

All lessons in Beginner