71

My React Native code:

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

import { StackNavigator } from 'react-navigation';
import DetailsPage from './src/screens/DetailsPage';

class HomeScreen extends React.Component {

   constructor() {
    super();
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      userDataSource: ds,
    };
  }

  componentDidMount(){
      this.fetchUsers();
  }

    fetchUsers(){

        fetch('https://jsonplaceholder.typicode.com/users')
            .then((response) => response.json())
            .then((response) => {
                this.setState({
                    userDataSource: this.state.userDataSource.cloneWithRows(response)
                });
            });
    }

    onPress(user){
        this.props.navigator.push({
            id: 'DetailPage'
        });
    }

  renderRow(user, sectionID, rowID, highlightRow){
      return(
      <TouchableHighlight onPress={()=>{this.onPress(user)} } >
      <View style={styles.row}>
        <Text style={styles.rowText}> {user.name} </Text>

      </View>
      </TouchableHighlight>
      )
  }


  render(){
      return(
          <ListView
            dataSource = {this.state.userDataSource}
            renderRow = {this.renderRow.bind(this)}
          />
      )
  } 
}

Navigation config:

const NavigationTest = StackNavigator({
  Home: { screen: HomeScreen },
  DetailsPage: { screen: DetailsPage },
});

The Details screens is:

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

import styles from '../styles';


export default class DetailsPage extends React.Component {
  static navigationOptions = ({ navigation }) => ({
    title: `User: ${navigation.state.params.user.name}`,
  });
  render() {
    const { params } = this.props.navigation.state;
    return (
      <View>
        <Text style={styles.myStyle}>Name: {params.name}</Text>
        <Text style={styles.myStyle}>Email: {params.email}</Text>
      </View>
    );
  }
}

I am not able to pass the user to the DetailsPage with the code:

onPress(user){
        this.props.navigator.push({
            id: 'DetailPage'
        });
    }

I want to navigate to the DetailPage with the onPress function. If I alert it like:

onPress(user){ Alert.alert(user.name)}

I do get the value, but how do I pass it to the other page?

Many thanks!

Somename
  • 3,376
  • 16
  • 42
  • 84

8 Answers8

134

You can pass params with the navigate function's second argument:

onPress(user) {
  this.props.navigation.navigate(
    'DetailPage',
    { user },
  );
}

React Navigation 5.x, 6.x (2022)

Access them in this.props.route.params. For example in your DetailsPage:

<Text style={styles.myStyle}>{this.props.route.params.user.name}</Text>

https://reactnavigation.org/docs/params/

React Navigation <= 4.x

Access them in this.props.navigation.state.params. For example in your DetailsPage:

<Text style={styles.myStyle}>{this.props.navigation.state.params.user.name}</Text>

https://reactnavigation.org/docs/4.x/params/

jjjjjjjjjjjjjjjjjjjj
  • 3,118
  • 1
  • 14
  • 14
  • 1
    Thanks. I was getting an error, I tried `'DetailPage', { users:user });` and It worked. I have another question if you could help please. Im trying to use a parameter from the user array, `id` to `fetch` data from another API, where and how can I use it? Trying to use it out of `fetch` by declaring, `var theId = '${navigation.state.params.users.id}` but its not working. Can you point me to the proper direction please? Many thanks. – Somename Jul 29 '17 at 16:31
  • Looks like a typo, try `${navigation.state.params.user.id}` (`user` instead of `users`) – jjjjjjjjjjjjjjjjjjjj Jul 29 '17 at 16:47
  • 1
    No, I've passed it as `users`, `'DetailPage', { users:user });`. Not sure where and how do I call for it in the `fetch`, please help. – Somename Jul 29 '17 at 17:17
  • I have added a button on HeaderRigh property in Static navigation options in component on that button i want to pass ref of method defined in component. But i am not able to pass that. Can you help – Robin Garg Mar 13 '18 at 13:41
  • 1
    @RobinGarg that's off topic, but you'll find the solution to your problem in this github issue: https://github.com/react-navigation/react-navigation/issues/147 – jjjjjjjjjjjjjjjjjjjj Mar 13 '18 at 14:40
  • @Somename I have same issue: Trying to retain 'this' inside fetching of info. Been stuck on it for days, get's caught up in the Worker rather than the proper scope of where the function is binded – webdevinci Aug 06 '18 at 11:30
  • any replacement for getParams in react navigation 5 as it says undefined method? – HarshitMadhav Jun 08 '20 at 14:03
  • @HarshitAgrawal You can substitute `this.props.navigation.getParam('foo', 'bar')` for `this.props.route.params.foo || 'bar'`. – jjjjjjjjjjjjjjjjjjjj Jun 11 '20 at 08:19
12

In react hooks, params send in navigation using useNavigation

import { useNavigation } from '@react-navigation/native';

const navigation = useNavigation();

<Button
      title="Back"
      onPress={() => {
        navigation.navigate('MyScreen',{name:'test'});
      }}
    />

then access them using useNavigationParam

function MyScreen() {
  const name = useNavigationParam('name');
  return <p>name is {name}</p>;
}
Aurangzaib Rana
  • 4,028
  • 1
  • 14
  • 23
11

See this .

It solved my problem.

this.props.navigation.navigate("**stack_Name**", {
 screen:"screen_name_connect_with_**stack_name**",
 params:{
 user:"anything_string_or_object"
}
})
4b0
  • 21,981
  • 30
  • 95
  • 142
GIRIRAJ NAGAR
  • 181
  • 1
  • 5
2

In your first page, say CountriesList

const CountriesList = ({ navigation }) => {

/* Function to navigate to 2nd screen */
  const viewCountry = (country) => {
    navigation.navigate('ListItemPageRoute', { name: country.country_name });
  };
}

For your second page name, say ListItemPageRoute

const ListItemPageRoute = (props) => {

return (
    <View style={styles.container}>
        <Text style={styles.countryText}> { props.route.params.name } </Text>
    </View>
  );
};

'Props.route' Object will have the list of all parameters you would like to pass from one screen to another.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Nishant Kohli
  • 445
  • 6
  • 6
1

for me, soved it by useNavigation() and useRoute():

For functional component:

import * as React from 'react';
import { Button } from 'react-native';
import { useNavigation } from '@react-navigation/native';

function MyBackButton() {
  const navigation = useNavigation();

  return (
    <Button
      title="Back"
      onPress={() => {
        navigation.goBack();
      }}
    />
  );
}

For class component:

class MyText extends React.Component {
  render() {
    // Get it from props
    const { route } = this.props;
  }
}

// Wrap and export
export default function(props) {
  const route = useRoute();

  return <MyText {...props} route={route} />;
}
rubal islam
  • 339
  • 3
  • 5
0

onPress={() => {this.props.navigation.navigate('AllImages', {Types: item.type })} console.log('valuesstrong text', this.props.route.params.Types);**

0

1)How to send data to another screen through params : onPress={(item) => props.navigation.navigate('Your ScreenName', {item : item})}

2)How to get data on another screen: const {item} = props.route.params

Muhammad Haidar
  • 1,541
  • 16
  • 17
-1

You can do it so easily.
You want to pass some parameters to your screen ? Do just that:

export default () => {
  
  const MainScreenComponent = ({navigation}) => (
    <MainScreen
      navigation={navigation}
      /**
      *
      * And here your parameters...
      *
      */
    />
  );

  const HomeScreenComponent = ({navigation}) => (
    <HomeScreen
      navigation={navigation}
      /**
      *
      * And here your parameters...
      *
      */
    />
  );

  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="MainScreen">
        <Stack.Screen name="MainScreen" component={MainScreenComponent}/>
        <Stack.Screen name="HomeScreen" component={MomeScreenComponent}/>
      </Stack.Navigator>
    </NavigationContainer>
  );
};
KAYZORK
  • 337
  • 1
  • 3
  • 17