Search code examples
react-nativestack-navigator

Parameters not passing in stack navigator in react native


I have a stack navigator:

import React from 'react';
import { createStackNavigator } from '@react-navigation/stack'
import MainScreen from './../screens/MainScreen';
import ServiceScreen from './../screens/ServiceScreen';

const Stack = createStackNavigator();

function HomeNavigator(){
    return(
    <Stack.Navigator screenOptions={{
        headerShown: false
    }}>
        <Stack.Screen name="MainScreen" component={MainScreen} />
        <Stack.Screen name="ServiceScreen" component={ServiceScreen} />
    </Stack.Navigator>
    );
}

export default HomeNavigator;

Now I have this line in a button press event in my MainScreen

navigation.navigate('ServiceScreen', {location: selectedLocation});

Service Screen: In here, ServiceApi is imported and is an apisauce post function. Also other things like separator and stuff are components I build.

function ServiceScreen({location}) {

    console.log(`ServicesScreen ${location}`);

    const [services, setServices] = useState();

    useEffect(() => {getServices()}, []);

    async function getServices(){
        const response = await ServicesApi.getServices();
        setServices(response.data);
    }

    if(!services) {
        return <AppText>No Services available!</AppText>
    }
    return (
        <Screen style={styles.container}>
            <View style={styles.location}>
                <AppText>{location}</AppText>
            </View>
                <Separator style={styles.separator} />
                <Separator style={styles.bar} />
            <ScrollView showsVerticalScrollIndicator={false}>
                {services.map(service => (
                    <View style={styles.subcat} key={service.id}>
                    <ServiceListItem name={service.name} img={servicePictures[service.img]} distance={service.distance} />
                    { service.id!=services[services.length-1].id && <Separator /> }
                    </View>
                ))}
            </ScrollView>  
        </Screen>
    );
}

I am navigated to the ServiceScreen but location is undefined


Solution

  • This is because params passed by navigation can be accessed in props.route.params. So in your case it would be:

    function ServiceScreen({route}) {
    
        console.log(`ServicesScreen ${route.params.location}`);

    https://reactnavigation.org/docs/params