Search code examples
javascriptreactjsreact-nativenavigationreact-navigation

react native : why my screen's param(props) can't be passed while using stack navigator?


App.js

const Stack = createNativeStackNavigator();

export default function App() {
  return (
    <Provider store={store}>
      <NavigationContainer>
        <Stack.Navigator initialRouteName="Main">
          <Stack.Screen options={{headerShown: false}} name="Main" component={MainScreen} />
          <Stack.Screen options={{headerShown: false}} name="Report" component={ReportScreen} />
        </Stack.Navigator>
      </NavigationContainer>
    </Provider>
  );
}

./screens/ReportScreen.js

import React from 'react';
import {
  StyleSheet,
  SafeAreaView,
  View,
  Text,
} from 'react-native';
import ReportReason from '../components/ReportReason';

const ReportScreen = ({route}) => {
    
    const textVal = '';
    if (route.param.title.length > 12){
        textVal = route.params.title.substring(0,10) + '...';
    }
    else {
        textVal = route.params.title;
    }
    
    return(
        <SafeAreaView style = {reportStyles.container}>
            <View style = {reportStyles.card}>
                <Text>Report</Text>
                <Text>{textval}</Text>
                <ReportReason/>
            </View>
        </SafeAreaView>
    );
};

part of ./components/ReportMension.js

const ReportMension = ({mension}) => {

return(

TouchableOpacity style={postModalStyles.listButton} onPress={()=>{
console.log(mension)
navigation.navigate('Report', { title: mension.title });
}}>
            <Text style={postModalStyles.text}>report</Text>
        </TouchableOpacity>

);
}

this is component of screen named Main.

console.log is operated normally. why my component and navigator are cannot passed params(props)? how to pass props when using stack navigaor??


Solution

  • First, in ReportMention, you can't reassign a const variable. Instead, try

        let textVal = '';
        if (route.params.title.length > 12) {
            textVal = route.params.title.substring(0,10) + '...';
        }
        else {
            textVal = route.params.title;
        }
    

    Or

    const textVal = route.params.title.length > 12
      ? route.params.title.substring(0,10) + '...'
      : route.params.title;
    

    Second, there's a typo in the condition: route.param.title.length should be route.params.title.length. This would throw an error, since you can't access the property length on an object that is undefined.

    These two syntax errors should prevent fast refresh from working, since the result wouldn't compile. If you fix these, and console.log the route object in ReportMention, you should get the params you're looking for.