Logo
Navigation
NavigationStack Navigation

Stack Navigation

Introduction to stack navigation, a fundamental navigation pattern where screens are stacked on top of each other.

What is Stack Navigation?

Stack navigation is one of the most commonly used navigation patterns in mobile applications. It allows users to navigate between different screens by pushing or popping them onto a stack. This is similar to how web browsers handle navigation history.

Installation

To implement stack navigation in a React Native project, you'll typically use a library like React Navigation. First, you need to install the necessary packages:

npm install @react-navigation/native @react-navigation/stack

or

yarn add @react-navigation/native @react-navigation/stack

Basic Usage

Overview

The basic idea is to have a stack of screens where you can push a new screen on top or pop a screen off.

Example

Here's a simple example to demonstrate stack navigation:

import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
 
const Stack = createStackNavigator();
 
const HomeScreen = () => <Text>Home Screen</Text>;
const DetailsScreen = () => <Text>Details Screen</Text>;
 
const App = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home">
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Details" component={DetailsScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
};
 
export default App;

Overview

You can navigate between screens using the navigation prop provided to screen components.

Example

Here's how you can navigate from the Home screen to the Details screen:

const HomeScreen = ({ navigation }) => {
  return (
    <Button
      title="Go to Details"
      onPress={() => navigation.navigate('Details')}
    />
  );
};

Customization

Overview

React Navigation provides various options for customizing the appearance and behavior of your stack navigator.

Example

Here's an example where we customize the header:

<Stack.Navigator
  screenOptions={{
    headerStyle: {
      backgroundColor: '#f4511e',
    },
    headerTintColor: '#fff',
    headerTitleStyle: {
      fontWeight: 'bold',
    },
  }}
>
  {/* screens */}
</Stack.Navigator>

Understanding stack navigation is crucial for building intuitive and user-friendly React Native applications. Feel free to explore the React Navigation documentation further to fully grasp its capabilities.

Book a conversation with us for personalize training today!

Was this helpful?
Logo