Search code examples
javascriptreactjsreact-nativereact-navigationreact-navigation-stack

undefined function when passing navigation AND props to a react native component (basic disconnect button)


I'm a complete newbie and I'm trying to have a stack navigator only accessible if the user is logged, which works, but I can't manage to have a correctly working disconnect button. I'm using a simple bool so far to grant access. The function used to disconnect, passed as a prop, is not found when I'm using the disconnect button.

App/Login screen :

const Stack = createStackNavigator();

export default function App() {
  const [userIsLogged, setUserLog] = useState(false);

  if (!userIsLogged) {
    return <LoginScreen setUserLog={setUserLog}/>;
  } else {
    return (
      <NavigationContainer>
        <Stack.Navigator>
          <Stack.Screen name="Home">
            {props => <Home {...props} setUserLog={setUserLog}/>}
          </Stack.Screen>
          <Stack.Screen name="Rooms" component={Rooms}/>
        </Stack.Navigator>
      </NavigationContainer>
    );
  }
}

Where the disconnect button is called:

const Home = ({navigation}, props) => {
  return (
    <View style={styles.container}>
      <Text>Home</Text>
      <TouchableOpacity onPress={() => props.setUserLog(false)}>
        <Text>DISCONNECT</Text>
      </TouchableOpacity>
      <TouchableOpacity onPress={() => navigation.navigate('Rooms')}>
        <Text>ACCESS TO ROOMS</Text>
      </TouchableOpacity>
      <StatusBar style="auto" />
    </View>
  );
};

(Code has been simplified heavily to only highlight my issue)


Solution

  • Change

    const Home = ({navigation}, props) => { 
    

    to

    const Home = (props) => {
    const {navigation} = props;
    
    return /* REST OF CODE */
    

    ({navigation}, props) doesn't split the props into two groups, it defines two arguments to your function. Which means props will always be undefined since you never pass a second argument in this case.