Passing Data Using React-Native Navigation

Viewed 74019

Im trying to pass data between screens in my app. Currently I am using


"react-native": "0.46.0",
"react-navigation": "^1.0.0-beta.11"

I have my index.js


 import React, { Component } from 'react';
    import {
      AppRegistry,
    } from 'react-native';
    import App from './src/App'
    import { StackNavigator } from 'react-navigation';
    import SecondScreen from './src/SecondScreen'    

    class med extends Component {
      static navigationOptions = {
        title: 'Home Screen',
      };

      render(){
        const { navigation } = this.props;

        return (
          <App navigation={ navigation }/>
        );
      }
    }

    const SimpleApp = StackNavigator({
      Home: { screen: med },
      SecondScreen: { screen: SecondScreen, title: 'ss' },    
    });

    AppRegistry.registerComponent('med', () => SimpleApp);

app as

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

    const App = (props)  => {
      const { navigate } = props.navigation;

      return (
        <View>
          <Text>
            Welcome to React Native Navigation Sample!
          </Text>
          <Button
              onPress={() => navigate('SecondScreen', { user: 'Lucy' })}
              title="Go to Second Screen"
            />
        </View>
      );
    }

    export default App

then in the secondscreen.js where we will fetch the data which passed from the previous screen as


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

    import { StackNavigator } from 'react-navigation';


    const SecondScreen = (props)  => {
      const { state} = props.navigation;
      console.log("PROPS" + state.params);


      return (
        <View>
          <Text>
            HI
          </Text>

        </View>
      );
    }

    SecondScreen.navigationOptions = {
      title: 'Second Screen Title',
    };

    export default SecondScreen

Whenever I console.log I get undefined.
https://reactnavigation.org/docs/navigators/navigation-prop The docs say every screen should have these values what am I doing wrong?

11 Answers

All the other answers now seem outdated. In the current react navigation version, ("@react-navigation/native": "^5.0.8",), you first pass value between one screen from another like this:

       function HomeScreen({ navigation }) {
      return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
          <Text>Home Screen</Text>
          <Button
            title="Go to Details"
            onPress={() => {
              /* 1. Navigate to the Details route with params, passing the params as an object in the method navigate */
              navigation.navigate('Details', {
                itemId: 86,
                otherParam: 'anything you want here',
              });
            }}
          />
        </View>
      );
    }

and then in the component you are redirecting, you get the data you passed like this:

function DetailsScreen({ route, navigation }) {
  /* 2. Get the param */
  const { itemId } = route.params;
  const { otherParam } = route.params;
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Details Screen</Text>
      <Text>itemId: {JSON.stringify(itemId)}</Text>
      <Text>otherParam: {JSON.stringify(otherParam)}</Text>
    </View>
  );
}

So, basically, the data now is inside this.props.route.params. In those examples above, I showed how to get them from functional components, but in class components is similar, I did something like this:

First I passed the data from this ProfileButton, within it's handleNavigate function, like this:


// these ProfileButton and ProfileButtonText, are a Button and a Text, respectively,
// they were just styled with styled-components 
<ProfileButton
 onPress={() => this.handleNavigate(item) 
  <ProfileButtonText>
      check profile
  </ProfileButtonText>
</ProfileButton>

where the handleNavigate goes like this:

   handleNavigate = user => {
        // the same way that the data is passed in props.route,
        // the navigation and it's method to navigate is passed in the props.
        const {navigation} = this.props;
        navigation.navigate('User', {user});
    };

Then, the function HandleNavigate redirects to the user page, which is a class component, and I get the data like this:

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

export default class User extends Component {
    state = {
        title: this.props.route.params.user.name,
    };


    render() {
        const {title} = this.state;
        return (
            <View>
                <Text>{title}</Text>
            </View>
        );
    }
}

In class components, the way I found out is making this quite long line title: this.props.route.params.user.name, but it works. If anyone knows how to make it shorter in the current version of react-native navigation, please enlighten me. I hope this solves your problem.

react-navigation 3.*

Parent Class

this.props.navigation.navigate('Child', {
    something: 'Some Value',
});

Child Class

this.props.navigation.state.params.something // outputs "Some Value"

From react navigaton 3.x docs, you can use getParam(params).

    class SecondScreen extends React.Component {
        render() {
          const { navigation } = this.props;
          const fname = navigation.getParam('user');
          return (
            <View>
              <Text>user: {JSON.stringify(fname)}</Text>
            </View>
          );
        }
    }

In 2021, You can fetch using

this.props.route.params.data

I have developed an NPM package for send data from one component to other components. Please do check and use its easy to use.

React data navigation

import { DataNavigation } from 'react-data-navigation';
.
.
.
// For set the data you need to call setData(key, value) Function i.e.
// eg. DataNavigation.setData('name', 'Viren'); 
// it will set the 'Viren' as respect to 'name' key.

import { DataNavigation } from 'react-data-navigation';
.
.
.
// Here we want to get the name value, which you set in home component than
// console.log('Hey my name is' + DataNavigation.getData('name'));
// it will print in console : Hey my name is Viren.

Comment down for any help.

Using Hooks

    Screen1.js
    
    navigation.navigate('Screen2',{ user_name: 'aaa',room_id:'100' });
    
    Screen2.js
    
    export default function Screen2({navigation){
              return(
                  <View>
           <Text> {navigation.getParams('user_name')} </Text>
               </View>   
                    )
                  }

Function Component.

First Screen
How to go in the another screen and also pass data from ono screen to another.

<TouchableOpacity onPress={()=>props.navigation.navigate("screenName",{name:'saurabh'})}>
</TouchableOpacity>

Second Screen
using the following ways we can get data from first screen in second screen.

props.navigation.state.params.name

Es6:

const Data= props.navigation.state.params.name;

Component(secondScreen):

const SecondScreen=(props)=>{
const Data= props.navigation.state.params;
 return(
   <View>
     <Text>{Data.name}</Text>
   </View>
  )
}

export default SecondScreen;

You can check Demo Here:

Related