React Native StackNavigator Pass & Get Params to Screen

Last Updated on by in React Native
In this tutorial, we are going to learn how to easily pass some value from one screen to another screen using React Navigation’s StackNavigator service.This is the most used task for almost every React Native 0.61.5 developer. In-app development, we often transfer id or some values to other routes. This process enables communication between the user and the application.

For example, we are on a blog page, and we want to visit the blog detail page and assume the blog detail page’s url contains the post id. So, to handle this kind of situation, we grab the post id and pass it to the post detail page to access the post detail page.

Here, in this post, we will learn to set or pass the id from one route to another route and also look at how to access the navigation prop via various methods.

Install React Native App

Run command from the terminal to install create-react-native-app tool.

sudo npm i -g create-react-native-app

Create a brand new React Native App using the below command.

create-react-native-app reactNativeNavigation

Allow Expo to be installed by selecting “Y” and don’t forget to download the Expo app in your mobile device based on the platform (iOS or Android).

Go inside the project directory.

cd reactNativeNavigation

Configure Navigation Packages

Next, Install the required React Navigation packages.

# for NPM
npm install @react-navigation/native

# for yarn
yarn add @react-navigation/native

Also, Install the following dependencies that is essential for navigators.

# for NPM
npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view

# for yarn
yarn add react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view

Adding Stack Navigator Package

To implement the stack navigator in React Native, we need to install the StackNavigator package.

# for NPM
npm install @react-navigation/stack

# for yarn
yarn add @react-navigation/stack

Create Screens

Now, we create Blog and Blog Detail screens and configure the navigation between these screens in a while.

Go to terminal and run the following command to generate the screens.

mkdir screens

touch screens/Blog.js
touch screens/BlogDetails.js

Open screen/Blog.js file and add the following code.

// screens/Blog.js

import React, { Component } from 'react';
import { Button, View, Text } from 'react-native';

class Blog extends Component {
  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Blog screen</Text>
      </View>
    );
  }
}

export default Blog;

Open screen/BlogDetails.js file and add the following code.

// screens/BlogDetails.js

import React, { Component } from 'react';
import { Button, View, Text } from 'react-native';

class BlogDetails extends Component {
  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Blog Details screen</Text>
      </View>
    );
  }
}

export default BlogDetails;

Adding Stack Navigator

Open App.js file and add the following code in the final App.js file. We are setting up stack navigation for Home, Blog, and Blog Details Page.

In the earlier tutorial, we have explained each and every step on how to create React Native Stack Navigation? tutorial. Check out the tutorial if you haven’t checked out yet.

// App.js

import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

import Blog from './screens/Blog';
import BlogDetails from './screens/BlogDetails';

const Stack = createStackNavigator();

function NavStack() {
  return (
     <Stack.Navigator
        initialRouteName="Blog"
        screenOptions={{
          headerTitleAlign: 'center',
          headerStyle: {
            backgroundColor: '#621FF7',
          },
          headerTintColor: '#fff',
          headerTitleStyle :{
            fontWeight: 'bold',
          },
        }}
      >
      <Stack.Screen 
        name="Blog" 
        component={Blog} 
        options={{ title: 'Blog' }}
      />
      <Stack.Screen 
       name="BlogDetails" 
       component={BlogDetails} 
       options={{ title: 'Blog Detail' }}
      />
    </Stack.Navigator>
  );
}

export default function App() {
  return (
    <NavigationContainer>
      <NavStack />
    </NavigationContainer>
  );
}

console.disableYellowBox = true;

Run command to start the app.

npm start

--- or ---

yarn start

Sending the Parameter to Screen

So far, we have seen how to configure StackNavigator with few routes and enable navigation between those screens. Let’s start understanding how to pass data or param to a route in react native application.

Pass params to a route by putting them in an object as a second parameter to the navigation.navigate function:

this.props.navigation.navigate('RouteName', { /* parameters goes here */ })

By using the props object, you can read the params in your screen as follows:

component: this.props.navigation.state.params. 

Open screen/Blog.js file and place the following code inside of it.

// screens/Blog.js

import React, { Component } from 'react';
import { Button, View } from 'react-native';

class Blog extends Component {

  constructor() {
    super();
  }

  render() {  
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Button
            title="Go to Blog Details"
            onPress={() => {
              this.props.navigation.navigate('BlogDetails', {
                postId: 3006,
                otherParam: 'Pass whatever you want here',
              });
            }}
          />
    </View>
    );
  }
}

export default Blog;

On button press event we have called the navigation.navigate(‘routeName’, {‘param’}) method, it takes 1st argument as the screen name where we would like to navigate to.

In the second parameter, we can set the params that we need to send to another screen. In our case, we have set the postId: 3006, and otherParam property, that we will extract in blog details page.

Getting Route Params

Add the following code inside the BlogDetails.js file.

// screens/BlogDetails.js

import React, { Component } from 'react';
import { Button, View, Text } from 'react-native';

class BlogDetails extends Component {

  constructor() {
    super();
  }

  render() {  
    // Access the postId and otherParam via Destructuring assignment
    const { postId, otherParam } = this.props.route.params;

    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        
        <Text>Post id is: {postId}</Text>
        <Text>{otherParam}</Text>

        <Button
            title="Go to Blog"
            onPress={() => {
              this.props.navigation.navigate('Blog');
            }}
          />
      </View>
    );
  }
}

export default BlogDetails;

We used the Destructuring assignment to access the props object, here we passed the postId and otherParam from the blog screen. Now, we can easily expose the post id and otherParam properties in the react-native view.

React Native Navigation Sending & Getting Route Param to Screen

Conclusion

Finally, React Native Stack Navigation 5.0 tutorial is over, in this tutorial, we learned how to simply pass and get the route parameters from one screen to another screen. I hope you liked this tutorial, please share this tutorial with others.

Happy Coding!