Passing Data Using React-Native Navigation

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?

Answers:

Answer

In your code, props.navigation and this.props.navigation.state are two different things. You should try this in your second screen:

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

the const {state} line is only here to get an easy to read code.

Answer

First Class

<Button onPress = {
  () => navigate("ScreenName", {name:'Jane'})
} />

Second Class

const {params} = this.props.navigation.state
Answer

react-navigation 3.*

Parent Class

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

Child Class

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

You can access your param which is user, with props.navigation.state.params.user in related component (SecondScreen).

Answer

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>
          );
        }
    }
Answer

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.

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.