React Native – Navigation || Pass Values one screen to another screen

In app development when created screens , some time we need to pass data from one screen to another screen . We will see that how shall we pass data from one screen not another using navigation route.

Value pass between screen fragment of code.

  1. create an object and pass as parameter in function navigation.navigate("RouteName" , {object}).
  2. receive the object by another component using route.params.

Example – 1

// In App.js in a new project

import * as React from 'react';
import { View, Text, SafeAreaView, Pressable, Alert } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';

function HomeScreen({navigation}) {
  return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' ,backgroundColor:'yellow'}}>
            <Text>Home Screen</Text>
            <Pressable onPress={()=>{
              navigation.navigate('Details', {name:"Jit", phone:'8888888888'})
            }} style={{backgroundColor: 'cyan', borderRadius:6, height:40, width:'80%', justifyContent:'center', alignItems:'center', marginTop: 20}}>
           <Text >Show Detail Screen</Text>
           </Pressable>
           
           
        </View>
   
  );
}

function DetailsScreen({navigation, route}) {
  const {name, phone} = route.params;
  return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor:'lightgray' }}>
          <Text style={{fontWeight:'bold'}}>Details Screen</Text>
          <Text>Name : {name}</Text>
          <Text>Phone : {phone}</Text>
          <Pressable onPress={()=>{
              navigation.goBack('Home')
            }} style={{backgroundColor: 'cyan', borderRadius:6, height:40, width:'80%', justifyContent:'center', alignItems:'center', marginTop: 20}}>
           <Text >Go Back To Home Screen</Text>
           </Pressable>

        </View>
  );
}

const Stack = createNativeStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Details" component={DetailsScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;

Output:

           

 

Get Navigation Instance:

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

function ComponentName() {
  const navigation = useNavigation();
}

Call Event on Screen load:

import React, {useEffect} from 'react'; 
function ComponentName({navigation}) { 
    useEffect(
       () => navigation.addListener('focus', () => alert('Screen was focused')),[]
    );
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *